nginx总结-常用命令
nginx常用命令
查看状态
nginx -v # 显示版本号(如 nginx/1.18.0)
nginx -V # 显示版本号及编译参数(如 --with-http_ssl_module)
ps aux | grep nginx #查看进程状态
启动
#直接启动(默认配置)主配置文件通常是 /etc/nginx/nginx.conf
sudo nginx
#指定配置文件启动
sudo nginx -c /path/to/nginx.conf
#前台启动(调试模式)方便查看日志输出
sudo nginx -g "daemon off;"
停止
#立即停止 Nginx 进程(不等待当前请求完成)。
sudo nginx -s stop
#强制停止(可能丢失未完成的请求)
sudo pkill nginx
# 或
sudo killall nginx
#优雅停止(系统服务方式)
sudo systemctl stop nginx # systemd 系统(如 Ubuntu 16.04+/CentOS 7+)
sudo service nginx stop # SysVinit 系统(如旧版 Ubuntu/CentOS)
重启
#重启服务(完整重启)(会短暂中断服务)
sudo systemctl restart nginx # systemd
sudo service nginx restart # SysVinit
重载配置(不中断服务)
sudo nginx -s reload
# 或
sudo systemctl reload nginx # systemd
测试配置文件
测试配置文件语法是否正确,并输出加载的配置路径。
#测试默认配置文件
sudo nginx -t
#测试指定位置的配置文件
sudo nginx -t -c /path/to/nginx.conf
输出如:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
会输出加载的配置文件路径,包括主配置文件和所有 include 的文件。第一行会明确显示主配置文件的路径
查看日志
tail -f /var/log/nginx/error.log # 错误日志
tail -f /var/log/nginx/access.log # 访问记录
docker操作nginx命令
拉取 Nginx 镜像
docker pull nginx[:tag] # 指定版本(如 nginx:1.27.1),不指定则拉取最新版
启动 Nginx 容器
docker run -d --name nginx -p 80:80 nginx # 基本启动命令
-d:后台运行容器(分离模式运行容器),并返回容器ID;
--name 指定容器名字
-p: 指定端口映射,格式为:主机(宿主)端口:容器端口
停止/重启/删除容器
docker stop nginx # 停止容器
docker restart nginx # 重启容器
docker rm nginx # 删除容器(需先停止)
查看容器状态
docker ps | grep nginx # 查看运行中的容器
docker logs nginx # 查看容器日志(调试用)
进入容器内部
docker exec -it nginx bash # 进入容器终端,可手动操作 Nginx
进入容器内部后,就可以使用nginx命令操作nginx了
nginx -t # 检查配置是否正确,避免重启失败
nginx -s reload # 修改配置后,平滑重启 Nginx
nginx -s stop # 立即停止(不推荐,可能丢失请求)
nginx # 启动 Nginx(若容器内无服务管理,通常通过 `docker restart` 替代)
配置文件、日志、静态资源 挂载
为避免容器删除后配置丢失,需将 配置文件、日志、静态资源 挂载到宿主机:
#创建宿主机目录
mkdir -p /data/nginx/{conf,log,html}
#启动容器并挂载目录
docker run -d --name nginx \
-p 80:80 \
-v /data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \ # 挂载主配置文件
-v /data/nginx/conf/conf.d:/etc/nginx/conf.d \ # 挂载虚拟主机配置
-v /data/nginx/log:/var/log/nginx \ # 挂载日志
-v /data/nginx/html:/usr/share/nginx/html \ # 挂载静态资源
nginx
修改配置后生效,直接编辑宿主机上的 /data/nginx/conf/nginx.conf。在容器内部执行 nginx -t 测试语法,再通过 nginx -s reload 重新加载
或在容器外执行 docker restart nginx
部署 HTTPS
#生成 SSL 证书(示例使用自签名证书)
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /data/nginx/ssl/nginx.key \
-out /data/nginx/ssl/nginx.pem
配置 Nginx(宿主机编辑 /data/nginx/conf/nginx.conf)
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/nginx.pem;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
root /usr/share/nginx/html;
index index.html;
}
启动容器并挂载 SSL 证书
docker run -d --name nginx \
-p 80:80 -p 443:443 \
-v /data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /data/nginx/ssl:/etc/nginx/ssl \
-v /data/nginx/html:/usr/share/nginx/html \
nginx

浙公网安备 33010602011771号