MENU

Ubuntu下-Nginx安装并设置开机自启

March 4, 2020 • Read: 318 • Nginx

开机自启

在/etc/init.d/目录下创建名为nginx的文件:

sudo touch /etc/init.d/nginx

编辑如下内容:

#!/bin/bash

set -e
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="nginx daemon"
NAME=nginx
DAEMON=/usr/local/nginx/sbin/$NAME
SCRIPTNAME=/etc/init.d/$NAME


# If the daemon file is not found, terminate the script.
test -x $DAEMON || exit 0

d_start() {
        $DAEMON || echo -n " already running"
}

d_stop() {
        $DAEMON –s quit || echo -n " not running"
}

d_reload() {
        $DAEMON –s reload || echo -n " could not reload"
}

case "$1" in
    start)
    echo -n "Starting $DESC: $NAME"
    d_start
    echo "."
    ;;
stop)
    echo -n "Stopping $DESC: $NAME"
    d_stop
    echo "."
    ;;
reload)
    echo -n "Reloading $DESC configuration..."
    d_reload
    echo "reloaded."
    ;;
restart)
    echo -n "Restarting $DESC: $NAME"
    d_stop
# Sleep for two seconds before starting again, this should give the
# Nginx daemon some time to perform a graceful stop.
    sleep 2
    d_start
    echo "."
    ;;
*)
    echo "Usage: $SCRIPTNAME {start|stop|restart|reload}" >&2
    exit 3
    ;;
esac
exit 0

脚本授权

chmod +x /etc/init.d/nginx

加入开机启动

sysv-rc-conf

界面说明(上下键切换到nginx选项,空格选中,q保存退出)

运行级别说明:
S   表示开机后就会运行的服务
0   表示关机
1   表示单用户模式  (类似windows的安全模式)
2   表示无网络服务的多用户模式
3   表示多用户模式
4   系统预留(暂没使用)
5   表示多用户图形模式
6   表示重启

233.png

其他命令(以下代码未测试)

#设置开机启动nginx
sudo update-rc.d –f nginx defaults
#移除nginx开机启动
update-rc.d -f nginx remove
#开启开机启动
sysv-rc-conf nginx on
#nginx操作命令
service nginx -s reload | stop | restart | start

兼总条贯 知至知终