Nginx shell系统自启服务脚本编写

Nginx Shell 自启动脚本


由于每次重启服务器后,nginx都需要手动启动,相当不便,所以写了个自启脚本
创建nginx脚本

cd /etc/init.d
vim nginx

#!/bin/sh
EXEC=/home/soft/nginx/sbin/nginx
PIDFILE=/home/soft/nginx/logs/nginx.pid
CONF="/home/soft/nginx/conf/nginx.conf"

case "$1" in
  start)
    if [ -f $PIDFILE ]
    then
	echo "$PIDFILE exists,process is already running or crashed"
    else
        echo "Starting Nginx Server..."
        $EXEC
    fi
    ;;
  stop)
      if [ ! -f $PIDFILE ]
      then
	  echo "$PIDFILE does not exists,process is not running"
      else
	  PID=$(cat $PIDFILE)
	  echo "Stopping..."
	  $EXEC -s quit
	  while [ -x /proc/${PID} ]
	  do
	    echo "Waiting for Nginx to shutdown ..."
	    sleep 1
	  done
	  echo "Nginx stopped"
    fi
    ;;
   reload)
    if [ ! -f $PIDFILE ]
    then 
	echo "$PIDFILE does not exists,process is not running"
    else
	echo "Nginx reload..."
	$EXEC -s reload
	echo $(ps -ef | grep nginx |grep $EXEC | grep -v grep | awk '{print $2}')
    fi
    ;;
    *)
    echo "Please use start or stop or reload as first argument"
        ;;
esac

增加权限

chmod a+x /etc/init.d/nginx

启用脚本

1、开启nginx开机自启,此项需要第二步操作
chkconfig nginx on
2、启动nginx
service nginx start
3、优雅停止nginx
service nginx stop
4、优雅的重新载入
service nignx reload

第二步是在/lib/systemd/system/目录下加入nginx.service

1、cd /lib/systemd/system/
2、vim nginx.service

[Unit]
Description=nginx.service
After=network.target 
[Service] 
Type=forking
#请添加你自己的路径
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target

1、开机自启动
systemctl enable nginx
2、启动
systemctl start nginx
3、停止
systemctl stop nginx
4、载入
systemctl reload nginx

你可能感兴趣的:(Nginx shell系统自启服务脚本编写)