CentOS 7 将 Nginx 添加为系统服务并设置开机自启
导语
在完成 Nginx 的编译安装并解决相关问题后,虽然 Nginx 能够正常运行,但尚未将其注册为系统服务。接下来的步骤是将 Nginx 纳入系统服务管理,并配置开机自启动功能。
查看服务
首先检查 Nginx 当前的服务状态,执行 systemctl status nginx 命令,输出结果如下所示:

结果显示未找到相关服务,因此需要手动添加系统服务配置。
添加系统服务
进入 /usr/lib/systemd/system 目录,新建 nginx.service 配置文件。请根据实际安装路径调整配置内容,详细解析可参考文末资料。具体配置内容如下:
[Unit]
Description=nginx - high performance web 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 -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
保存配置后,再次检查服务状态。

设置开机自动启动
先进行重启测试,观察 Nginx 服务是否随系统启动。

确认服务未自动启动后,手动输入 systemctl start nginx 命令进行启动。

通过 systemctl 命令验证,说明之前创建的 nginx.service 配置文件有效。随后执行 systemctl enable nginx 命令以设置开机自启动。

最后重启服务器,验证设置是否生效。

经检查一切正常,至此 Nginx 的编译安装及服务配置已完成,后续将进行 PHP 的安装。
参考资料:CentOS 7 systemd添加自定义系统服务、