编写Nginx服务控制脚本

Posted HzdWwZz"LJF

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了编写Nginx服务控制脚本相关的知识,希望对你有一定的参考价值。

./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启动时才能平稳加载

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

判断Nginx服务是否正在运行的方法:

当Nginx服务正在运行,会有nginx.pid这个文件:

[[email protected] sbin]# cat /application/nginx/logs/nginx.pid 
1664

当Nginx服务停止,就找不到该文件

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


[[email protected] 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服务控制脚本的主要内容,如果未能解决你的问题,请参考以下文章

脚本实现一键部署Nginx软件(Web服务器):

nginx启动脚本编写

nginx 源码编译安装并编写服务启动脚本

openresty编写代码怎么用命令启动和执行

shell脚本之一键部署web服务器Nginx,日常解放双手!

编写python3脚本监控Nginx服务状态