一、通过yum安装nginx 获取nginx的启动脚本(或直接复制我下面的脚本,只需要改变路径即可)



/usr/lib/systemd/system/nginx.service


脚本内容如下:



[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /var/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /var/run/nginx.pid)"

[Install]
WantedBy=multi-user.target


  二、修改路径

    1、修改二进制文件路径

我这里安装的路径是:



/apps/nginx/sbin/nginx


配置文件路径是:



/apps/nginx/conf/nginx.conf


修改下面这行:



ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf


修改为:



ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf


     2、修改PID文件路径

##  PID文件路径要和nginx配置中的路径一样,pid文件和配置文件中不一样,会导致这个脚本永不了,默认没配置,这里修改配置文件

/apps/nginx/conf/nginx.conf 取消注释pid这行



pid        logs/nginx.pid;


##  这里的log是我安装目录里的logs。我安装的位置是/apps/nginx/

修改这行:



PIDFile=/var/run/nginx.pid


修改为:



PIDFile=/apps/nginx/logs/nginx.pid



[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/apps/nginx/logs/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /apps/nginx/logs/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /apps/nginx/logs/nginx.pid)"

[Install]
WantedBy=multi-user.target


 ##  标绿的两行,看配置模板文件版本可能需要修改,也可能不需要修改,我这里使用的是nginx/1.20.1 版的配置文件,这里的路径不修改不会影响开启和关闭,但当我Systemctl reload nginx 时候会提示错误:“Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.“”记得修改完之后systemctl daemon-reload下

  三、将修改好的配置移动到:



/usr/lib/systemd/system


   四、测试:



1、停止nginx服务
systemctl stop nginx
2、开启nginx服务
systemctl start nginx
3、重读nginx配置文件(会回收之前空闲的工作进程,并启动新的工作进程)
systemctl reload nginx