# 将nginx设置成服务,并实现开机自动启动

# 说明:作者仅在CentOS7.0上进行了测试,而且没有进行可靠性和稳定性的测试!

cp /tmp/nginx /etc/rc.d/init.d/nginx
chmod +x /etc/rc.d/init.d/nginx
chkconfig --add nginx
chkconfig nginx on


/tmp/nginx文件的内容如下:

#! /bin/sh
#chkconfig: 2345 50 90

DESC="nginx daemon"
NAME=nginx
INSTALLDIR=/opt/nginx
DAEMON=$INSTALLDIR/sbin/$NAME
CONFIGFILE=$INSTALLDIR/conf/$NAME.conf
PIDFILE=$INSTALLDIR/logs/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

set -e
[ -x "$DAEMON" ] || exit 0

do_start() {
    $DAEMON -c $CONFIGFILE || echo -n "nginx already running"
}

do_stop() {
    kill -INT `cat $PIDFILE` || echo -n "nginx not running"
}

do_reload() {
    kill -HUP `cat $PIDFILE` || echo -n "nginx can't reload"
}

case "$1" in
    start)
        echo -n "Starting $DESC: $NAME"
        do_start
        echo "."
    ;;
    stop)
        echo -n "Stopping $DESC: $NAME"
        do_stop
        echo "."
    ;;
    reload|graceful)
        echo -n "Reloading $DESC configuration..."
        do_reload
        echo "."
    ;;
    restart)
        echo -n "Restarting $DESC: $NAME"
        do_stop
        do_start
        echo "."
    ;;
    *)
    echo "Usage: $SCRIPTNAME {start|stop|reload|restart}" >&2
    exit 3
    ;;
esac

exit 0


使用命令如下:

service nginx start
service nginx stop
service nginx reload
service nginx restart