Nginx 启动停止与重载
Nginx 的日常维护围绕两个入口:systemd 服务(systemctl 命令)与 Nginx 自身的信号机制(nginx -s 参数)。前者管理整个服务生命周期,后者用于平滑改配置、重开日志。
systemctl 管理服务
主流发行版安装后都会注册 nginx.service,推荐用 systemctl 管理:
sudo systemctl start nginx # 启动
sudo systemctl stop nginx # 停止
sudo systemctl restart nginx # 重启(先停后起,有短暂中断)
sudo systemctl reload nginx # 平滑重载配置,不断开已建立的连接
sudo systemctl enable nginx # 设置开机自启
sudo systemctl status nginx # 查看运行状态
status 显示 active (running) 即为正常;显示 failed 则参考下文"启动失败的常见原因"排查。
平滑重载与信号:nginx -s
nginx -s 向 master 进程发送信号,常用四个子命令:
| 命令 | 信号 | 行为 |
|---|---|---|
| nginx -s stop | TERM | 立即停止,正在处理的请求可能被切断 |
| nginx -s quit | QUIT | 优雅退出,处理完当前请求再停止 |
| nginx -s reload | HUP | 重读配置文件并平滑重载,旧 worker 处理完存量连接后退出 |
| nginx -s reopen | USR1 | 重新打开日志文件(配合 logrotate 做日志切割) |
reload 是运维最高频操作:先 nginx -t 校验语法,通过后再 reload,配置写错也不会影响正在运行的实例:
sudo nginx -t && sudo systemctl reload nginx
# 输出:nginx: configuration file /etc/nginx/nginx.conf test is successful
master / worker 进程模型
Nginx 运行时有两类进程:1 个 master 负责读取配置、监听信号、管理 worker;多个 worker 真正处理请求(数量由 worker_processes 决定)。用 ps 可直观看到:
ps -ef | grep nginx
# 输出:root 1261 1 0 ... nginx: master process nginx
# www-data 1262 1261 0 ... nginx: worker process
启动失败的常见原因
启动失败先看错误日志 /var/log/nginx/error.log,再按下表逐项排查:
| 现象 | 常见原因 | 处理 |
|---|---|---|
| bind() to 0.0.0.0:80 failed | 80 端口已被其他进程占用 | ss -lntp 查出占用进程并释放端口 |
| configuration file test failed | 配置语法错误 | 按 nginx -t 提示的文件与行号修改 |
| Permission denied | 日志或站点目录权限不足 | 检查目录属主是否与 user 指令一致 |
| 服务反复重启失败 | 磁盘满 / 内存不足 | df -h、free -m 检查资源 |
sudo nginx -t # 第一步:先校验语法
sudo tail -50 /var/log/nginx/error.log # 第二步:看错误日志定位
小结:日常记住两条命令即可——改完配置先 nginx -t 校验再 systemctl reload 生效;启动失败时先看 error.log 与端口占用,多数问题几分钟内可定位。