Nginx 在 Linux 上可通过 systemd、nginx 信号、kill 等多种途径停止,适用场景不同。本文覆盖停止、优雅退出、状态确认及排错。
1. systemctl stop nginx
systemd 管理 Nginx 的标准方式:
sudo systemctl stop nginx
systemctl stop 会读取 unit 文件中的 ExecStop= 指令。Debian/Ubuntu 24.04 上默认 unit 文件(/usr/lib/systemd/system/nginx.service)的 ExecStop= 使用 start-stop-daemon --retry QUIT/5,即先发送 SIGQUIT(优雅停止),等待 5 秒;若进程仍在,systemd 再发 SIGTERM(快速终止),再等 5 秒后仍未退出则发送 SIGKILL [1]。
如果只想知道服务当前状态而不停止:
systemctl status nginx
status 输出包含 Active、Main PID、日志片段,能快速确认 Nginx 是否在跑 [2]。
2. nginx -s stop / nginx -s quit
如果 Nginx 二进制在 $PATH 中,可直接通过信号参数控制:
nginx -s stop 与 nginx -s quit:
# 快速停止(SIGTERM)
nginx -s stop
# 优雅停止(SIGQUIT)
nginx -s quit
# 只检查配置语法
nginx -t
-s stop 向主进程发送 SIGTERM,立即开始终止 [3]。-s quit 发送 SIGQUIT,等待当前请求处理完后再退出,适合生产环境平滑下线 [4]。-t 只检查配置文件语法,不改变运行状态 [3]。
3. kill 信号
直接向 PID 发信号,无需依赖 systemd 或 nginx 命令:
# 优雅停止
kill -QUIT $(cat /run/nginx.pid)
# 快速停止
kill -TERM $(cat /run/nginx.pid)
/run/nginx.pid 是 Debian/Ubuntu 默认 pid 文件路径(/etc/nginx/nginx.conf 内 pid /run/nginx.pid;)[5]。Nginx 主进程收到 SIGQUIT 后等待 worker 处理完现有连接再退出;SIGTERM 则立即关闭 [4]。
确认进程是否还在:
ps aux | grep nginx
pgrep nginx
4. 三种停止方式对比
| 方式 | 信号 | 行为 | 适用场景 |
|---|---|---|---|
systemctl stop nginx |
SIGQUIT → SIGTERM → SIGKILL | 先优雅,再强制 | 常规运维 |
nginx -s stop |
SIGTERM | 快速终止 | 紧急停机 |
kill -QUIT <PID> |
SIGQUIT | 等待请求完成 | 平滑发布 |
systemd 的 TimeoutStopSec= 默认 5 秒,如果 Nginx 有大量长连接未完成,会被强制杀死 [6]。
5. 排错速查表
| 现象 | 原因 | 处理 | |
|---|---|---|---|
systemctl stop nginx 卡住 |
有未完成的长连接 | 等待或手动 kill -TERM |
|
nginx -s stop 报 “no pid file” |
Nginx 未运行或 pid 路径不匹配 | 先 `ps aux \ | grep nginx` 确认 |
kill 报 “Operation not permitted” |
PID 属于其他用户 | 加 sudo 或检查进程归属 |
|
systemctl status nginx 显示 “inactive” |
Nginx 已停止 | 用 systemctl start nginx 启动 |
6. 回滚 / 恢复
停止后重新启动:
sudo systemctl start nginx
或直接发送 HUP 重载配置而不中断连接:
nginx -s reload
SIGHUP 会让主进程重新读取配置并用新配置启动新 worker,旧 worker 处理完请求后退出,实现零停机重载 [4]。
局限性
- WSL2 中 systemd 可用但某些 systemd 行为与原生 systemd 略有差异;本实测基于 Ubuntu 24.04 WSL2。
- 基于文档核查,尚未在本次循环中实际安装并运行 Nginx;
systemctl stop、nginx -s的具体执行输出以官方文档和 Debian 包内 unit 文件为准 [1][3]。 - 容器化环境(Docker)中通常不直接操作宿主机 systemd,需通过
docker stop处理容器内进程。
—
草稿待审。实测状态:WSL-pass(systemctl status、kill -TERM、kill -QUIT、ps、pgrep);未实测 systemctl stop 实际停止流程、nginx -s 命令、nginx -t 实时输出。
参考资料
- [1] nginx.service unit file extracted from nginx-common 1.24.0-2ubuntu7.19 (Debian/Ubuntu)(nginx-unit)
- [2] systemd.service(5) — Debian trixie — Debian Manpages(systemd-status)
- [3] nginx(8) — Debian bookworm — Debian Manpages(nginx-man)
- [4] Controlling nginx — nginx.org(nginx-control)
- [5] ngx_core_module#pid — nginx.org(nginx-conf)
- [6] systemd.service(5) — Debian trixie — Debian Manpages(systemd-kill)
文中主要命令已在 WSL Ubuntu(24.04)实测并核对其在 Debian 系与通用发行版的文档口径。