nginx的启动脚本


问题:在预编译安装nginx时候每次启动时都非常不方便,所以想了下写个nginx脚本在/etc/init.d目录下可实现service的方式启动、停止、重启这样就方便多了!

 

[root@cml init.d]# vim nginxd

#!/bin/bash

#chkconfig: 2345 20 80


prog="nginxd"

nginx_bin="/usr/local/nginx/sbin/nginx"

 

if [ -x $nginx_bin ]; then   ##if语句判断是否存在nginx路径

    echo  "$nginx_bin is installled !"     

else

    echo -n "$nginx_bin not installed !"      

    exit 5

fi

 

start(){

    echo -n "starting $prog:"

    $nginx_bin -t          ##测试nginx配置文件

    a=$?

    if [ $a -eq 0 ]; then    ###if语句判断上一句是否执行成功

        touch /tmp/nginx.pid        ##创建一个nginx.pid文件后启动nginx

        $nginx_bin

    else

        echo "please check your nginx config"    

        exit 10

    fi

}

 

stop(){

    echo -n $"stopping $prog:"

    $nginx_bin -s stop            ##停止nginx

            a=$?

    if [ $a -eq 0 ]; then          ##判断执行上一句成功就删除nginx.pid文件输出信息

        rm -rf /tmp/nginx.pid

        echo "success stop nginx"

    else

        echo "check your nginx command"

        exit 11

    fi

}

 

case $1 in  ##

        start)

            start

;;

        stop)

            stop

;;

        reload|restart)

            stop

sleep 2

start

;;

        *)

            echo "Usage:$0{start|stop|reload/restart}"

        ;;

esac

 

验证:


[root@cml init.d]# service nginxd start

/usr/local/nginx/sbin/nginx is installled !

starting nginxd:nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok

nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

nginx: [emerg] still could not bind()

 

[root@cml init.d]# service nginxd stop

/usr/local/nginx/sbin/nginx is installled !

stopping nginxd:success stop nginx

[root@cml init.d]# service nginxd start

/usr/local/nginx/sbin/nginx is installled !

starting nginxd:nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok

nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

[root@cml init.d]# service nginxd restart

/usr/local/nginx/sbin/nginx is installled !

stopping nginxd:success stop nginx

starting nginxd:nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok

nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful