将源码安装的 Nginx 纳入 systemd 管理
适用于通过源码编译安装(默认路径
/usr/local/nginx)的 Nginx,配置完成后即可使用systemctl统一管理,并支持开机自启。
一、背景
源码编译安装的 Nginx 默认不带 systemd 服务单元,只能通过 ./nginx、nginx -s stop 等命令手动启停,无法使用 systemctl、也不能开机自启。
通过手动创建一个 nginx.service 单元文件,即可把它纳入 systemd 规范管理,享受以下能力:
systemctl start/stop/reload/restart nginx统一启停systemctl status nginx查看运行状态systemctl enable nginx开机自启- 进程异常退出时自动拉起
- 日志统一接入 journalctl
二、创建服务单元文件
创建文件 /usr/lib/systemd/system/nginx.service,内容如下(路径需与本机实际安装位置一致):
ini
[Unit]
Description=The NGINX HTTP and reverse proxy server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=multi-user.target
关键参数说明
| 参数 | 作用 |
|---|---|
Type=forking |
Nginx 以守护进程方式后台运行并 fork,systemd 通过 PID 文件跟踪主进程 |
PIDFile |
指向 nginx.pid,须与实际路径一致,否则 systemd 会误判进程状态 |
ExecStartPre=...nginx -t |
启动前先做配置语法检查,配置有误则不启动 |
ExecStart |
启动 Nginx |
ExecReload=...-s reload |
平滑重载配置,不中断业务 |
ExecStop=...-s quit |
优雅停止,处理完当前请求再退出 |
Restart=on-failure |
进程异常退出时自动拉起(正常 stop 不触发) |
WantedBy=multi-user.target |
多用户运行级别下生效,支持开机自启 |
也可以用以下命令一次性写入,避免编辑器粘贴问题:
bashcat > /usr/lib/systemd/system/nginx.service <<'EOF' [Unit] Description=The NGINX HTTP and reverse proxy server Documentation=http://nginx.org/en/docs/ After=network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid ExecStartPre=/usr/local/nginx/sbin/nginx -t ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true Restart=on-failure RestartSec=5s [Install] WantedBy=multi-user.target EOF
三、重载配置并设置开机自启
bash
# 重载 systemd,识别新服务
systemctl daemon-reload
# 设置开机自启
systemctl enable nginx
四、切换为 systemd 托管
若 Nginx 当前是手动启动的,直接 systemctl start 会因端口被占用而失败,需先停掉手动进程,再由 systemd 拉起:
bash
# 1. 优雅停止手动启动的 nginx
/usr/local/nginx/sbin/nginx -s quit
# 2. 确认进程已退出、端口已释放
sleep 2
ps aux | grep nginx
# 3. 由 systemd 启动
systemctl start nginx
切换瞬间会有约 1~2 秒中断,建议放在低峰期或维护窗口执行。
五、验证
bash
systemctl status nginx
看到 Active: active (running)、Main PID 有值、且显示 master + worker 进程即表示接管成功。
再验证业务与重载功能:
bash
systemctl reload nginx # 平滑重载
systemctl status nginx # 仍为 active (running)
curl -I http://127.0.0.1:端口 # 业务正常返回
六、常用命令速查
bash
systemctl status nginx # 查看状态
systemctl start nginx # 启动
systemctl stop nginx # 停止
systemctl reload nginx # 平滑重载配置(推荐,不中断)
systemctl restart nginx # 重启(有短暂中断)
systemctl enable nginx # 开机自启
systemctl disable nginx # 关闭开机自启
journalctl -u nginx -e # 查看 systemd 收集的日志
七、注意事项
- 统一用 systemctl 管理 ,不要再混用
./nginx手动启停,否则会导致 systemd 记录的状态与实际进程不一致。 - PIDFile 路径必须准确,写错会导致 systemd 无法正确跟踪进程。
- 修改单元文件后 需执行
systemctl daemon-reload才会生效。 Restart=on-failure可在进程异常崩溃时自动拉起,提升服务健壮性。