1. 程式人生 > >編寫Nginx服務控制腳本

編寫Nginx服務控制腳本

運行 case top bogon Opens module prefix cat code

./configure --user=www --group=www --prefix=/application/nginx --sbin-path=/application/nginx/sbin --conf-path=/application/nginx/conf/nginx.conf --error-log-path=/application/nginx/logs/error.log --http-log-path=/application/nginx/logs/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/lock/subsys/nginx --with-openssl=/app/openssl-1.0.2p --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-pcre

所以nginx的管理命令為

啟動: /application/nginx/sbin/nginx

停止:/application/nginx/sbin/nginx -s stop

重新加載:/application/nginx/sbin/nginx -s reload

**註意 reload只有Nginx啟動時才能平穩加載

[root@bogon sbin]# ./nginx -s reload
nginx: [error] open() "/application/nginx/logs/nginx.pid" failed (2: No such file or directory)

判斷Nginx服務是否正在運行的方法:

當Nginx服務正在運行,會有nginx.pid這個文件:

[root@bogon sbin]# cat /application/nginx/logs/nginx.pid 
1664

當Nginx服務停止,就找不到該文件

[root@bogon sbin]# ./nginx -s stop
[root@bogon sbin]# cat /application/nginx/logs/nginx.pid 
cat: /application/nginx/logs/nginx.pid: No such file or directory


[root@bogon tmp]# cat nginx.sh 
#!/bin/bash
[ -e /etc/init.d/functions ]&& . /etc/init.d/functions
pidfile=/application/nginx/logs/nginx.pid
Start_Nginx (){
        if [ -f $pidfile ];
then
        echo "Nginx is Running"
else
        /application/nginx/sbin/nginx > /dev/null 2>&1
        action  "Nginx is Started" /bin/true
        fi
}

Stop_Nginx (){
        if [ -f $pidfile ];
then
        /application/nginx/sbin/nginx -s stop > /dev/null 2>&1
        action "Nginx is Stopped" /bin/true
else
        action "Nginx is Stopped" /bin/false
        fi
}

Reload_Nginx (){
        if [ -f $pidfile ];
then
        /application/nginx/sbin/nginx -s reload > /dev/null 2>&1
        action "Nginx is Reloaded" /bin/true
else
        echo "Can‘t Open $pidfile ,no such file or directory"
fi
}
case $1 in
start)
        Start_Nginx
        RETVAL=$?
        ;;
stop)
        Stop_Nginx
        RETVAL=$?
        ;;
restart)
        Stop_Nginx
        sleep 3
        Start_Nginx
        RETVAL=$?
        ;;
reload)
        Reload_Nginx
        RETVAL=$?
        ;;
*)
        echo "USAGE:$0 {start|stop|restart|reload}"
        exit 1
esac
exit $RETVAL

給予該腳本執行權限

然後給/etc/rc.d/rc.local執行權限

在rc.local文件最後加上
/tmp/nginx.sh start

這樣開機就可以自動啟動nginx了

編寫Nginx服務控制腳本