源码安装nginx后需手动创建systemd服务文件实现开机自启与状态管理;确认路径(如/usr/local/nginx/sbin/nginx)、配置execstart等参数,执行daemon-reload、start、enable、status完成启用。

Linux 下为 Nginx 编写 systemd 服务文件,核心是让 systemd 能正确启动、监控和管理 Nginx 进程。关键不在于“写多复杂”,而在于匹配你的安装方式(包管理器安装 or 源码编译)和运行模式(是否启用 systemd 集成)。
确认 Nginx 安装路径和运行方式
这是后续配置的基础,必须先搞清楚:
- 主程序位置:源码安装通常在 /usr/local/nginx/sbin/nginx;包管理器安装(如 apt/yum)多为 /usr/sbin/nginx。用
which nginx或nginx -V 2>&1 | grep "configure arguments"确认 - 配置文件路径:默认是 /usr/local/nginx/conf/nginx.conf 或 /etc/nginx/nginx.conf
- 是否支持 systemd 通知:执行
nginx -V 2>&1 | grep systemd,若输出含--with-systemd,说明可启用Type=notify;否则只能用Type=forking - 日志与 PID 文件位置:源码安装常设为 /usr/local/nginx/logs/nginx.pid;包管理器安装多为 /run/nginx.pid 或 /var/run/nginx.pid
编写标准的 nginx.service 文件
统一放在 /etc/systemd/system/nginx.service(优先级高于系统自带,且升级不覆盖):
✅ 若 Nginx 编译时启用了 --with-systemd(推荐):
[Unit] Description=The NGINX HTTP and reverse proxy server Documentation=man:nginx(8) After=network.target remote-fs.target nss-lookup.target Wants=network-online.target [Service] Type=notify PIDFile=/run/nginx.pid ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;' ExecStart=/usr/sbin/nginx -g 'daemon off; master_process on;' ExecReload=/usr/sbin/nginx -g 'daemon off; master_process on;' -s reload ExecStop=/bin/kill -s QUIT $MAINPID KillSignal=SIGQUIT TimeoutStopSec=5 KillMode=mixed Restart=on-failure RestartSec=3 RuntimeDirectory=nginx RuntimeDirectoryMode=0755 [Install] WantedBy=multi-user.target
✅ 若为源码安装且未启用 systemd 支持(常见情况):
[Unit] Description=The NGINX HTTP and reverse proxy server After=network.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/bin/kill -s TERM $MAINPID Restart=on-failure RestartSec=3 User=root Group=root [Install] WantedBy=multi-user.target
注意点:
-
ExecStartPre必须校验配置,避免启动失败静默退出 -
PIDFile路径需与 Nginx 实际生成的 pid 文件一致(由pid指令在 nginx.conf 中指定) - 非 root 用户运行时,务必设置
User/Group并确保其对 conf、logs、html 有读写权限
启用并验证服务
写完文件后,四步走即可生效:
- 重载 systemd 配置:
sudo systemctl daemon-reload - 启动服务:
sudo systemctl start nginx - 设为开机自启:
sudo systemctl enable nginx - 检查状态:
sudo systemctl status nginx(看 Active 是否为 active (running),并确认无红色报错)
如果启动失败,用 sudo journalctl -u nginx -n 50 -xe 查看最近日志,多数问题出在路径错误、权限不足或配置语法异常。
常见适配要点
不是所有环境都一样,注意这些典型差异:
-
路径替换:把示例中所有
/usr/sbin/nginx或/usr/local/nginx/sbin/nginx替换成你实际的路径 -
配置文件指定:如果 nginx.conf 不在默认路径,
ExecStart和ExecStartPre后要加-c /your/path/nginx.conf - SELinux 或 AppArmor:若系统启用了强制访问控制,可能需额外策略放行 Nginx 对端口或目录的访问
-
防火墙:确保 80/443 端口已开放(
sudo ufw allow 'Nginx Full'或sudo firewall-cmd --permanent --add-service=http)
不复杂但容易忽略细节,理清路径、类型、权限这三点,基本就能稳住。











