为源码安装的nginx编写系统管理脚本需确保路径、用户、pid文件严格一致:推荐systemd(centos 7+/ubuntu 16.04+)或sysv init(centos 6),须指定/usr/local/nginx路径、nginx用户及正确pidfile,并验证配置语法与进程状态。

为 Nginx 源码安装版本编写系统管理脚本(如 /etc/init.d/nginx 或 systemd service 文件),核心是让系统能识别 Nginx 进程、正确启动/停止/重载,并支持开机自启。源码安装默认不带这些,需手动补全。
确认源码安装路径与用户权限
脚本必须知道 Nginx 的真实路径和运行身份,否则启停会失败:
-
安装前约定路径:推荐统一使用
/usr/local/nginx(configure 时用--prefix=/usr/local/nginx) -
检查二进制路径:
/usr/local/nginx/sbin/nginx -
确认配置文件路径:
/usr/local/nginx/conf/nginx.conf -
运行用户:默认是
nobody,但建议在nginx.conf中显式设为user nginx;,并创建系统用户useradd -r -s /sbin/nologin nginx
方式一:systemd 服务(推荐,CentOS 7+/Ubuntu 16.04+)
创建 /etc/systemd/system/nginx.service:
<font color="#666666"><pre class="brush:php;toolbar:false;">[Unit] Description=The NGINX HTTP and reverse proxy server After=network.target <p>[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 -c /usr/local/nginx/conf/nginx.conf ExecStop=/usr/local/nginx/sbin/nginx -s stop -c /usr/local/nginx/conf/nginx.conf Restart=on-failure RestartSec=3 User=nginx Group=nginx</p><p>[Install] WantedBy=multi-user.target </p>
启用服务:
systemctl daemon-reloadsystemctl enable nginxsystemctl start nginx
方式二:SysV init 脚本(兼容老系统,如 CentOS 6)
创建 /etc/init.d/nginx,赋予可执行权限(chmod +x):
<font color="#666666"><pre class="brush:php;toolbar:false;">#!/bin/bash
# chkconfig: - 85 15
# description: NGINX Startup Script
# processname: nginx
<p>NGINX="/usr/local/nginx/sbin/nginx"
CONF="/usr/local/nginx/conf/nginx.conf"
PID="/usr/local/nginx/logs/nginx.pid"
LOCK="/var/lock/subsys/nginx"</p><p>start() {
if [ -f $PID ] && kill -0 $(cat $PID) > /dev/null 2>&1; then
echo "nginx is already running"
return 1
fi
$NGINX -t -c $CONF || return 1
$NGINX -c $CONF
touch $LOCK
echo "nginx started"
}</p><p>stop() {
if [ ! -f $PID ] || ! kill -0 $(cat $PID) > /dev/null 2>&1; then
echo "nginx is not running"
rm -f $LOCK
return 1
fi
$NGINX -s stop
rm -f $LOCK $PID
echo "nginx stopped"
}</p><p>reload() {
$NGINX -t -c $CONF || return 1
$NGINX -s reload
echo "nginx reloaded"
}</p><p>case "$1" in
start) start ;;
stop) stop ;;
restart) stop; sleep 1; start ;;
reload) reload ;;
*) echo "Usage: $0 {start|stop|restart|reload}"; exit 1 ;;
esac
</p>
注册到系统服务:
chkconfig --add nginxchkconfig nginx onservice nginx start
验证与调试要点
脚本写完别急着用,先人工验证关键环节:
- 手动执行
/usr/local/nginx/sbin/nginx -t确保配置语法正确 - 检查
nginx.conf中pid指令是否与脚本中PIDFile一致(默认就是logs/nginx.pid) - 启动后用
ps aux | grep nginx和netstat -tlnp | grep :80确认进程和端口 - systemd 下查日志:
journalctl -u nginx -n 20 -f - init 脚本下加
set -x开头可输出执行过程,方便排错
不复杂但容易忽略细节,关键是路径、用户、PID 文件三者严格对应。选 systemd 还是 init 脚本,取决于你的系统版本和运维习惯。











