Linux系统service服务管理方式下Nginx设置开机启动

service命令其实是去/etc/init.d目录下,去执行相关程序,相应脚本需要自己填写。

1.设置nginx启动脚本

/etc/init.d/目录下创建nginx的启动文件
命令 vim /etc/init.d/nginx,将以下代码复制进去保存即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0.2 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
# It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: /usr/local/nginx/conf/nginx.conf
nginx=/usr/local/nginx/sbin/nginx
conf=/usr/local/nginx/conf/nginx.conf
case $1 in
start)
echo -n "Starting Nginx"
$nginx -c $conf
echo " done."
;;
stop)
echo -n "Stopping Nginx"
killall -9 nginx
echo " done."
;;
test)
$nginx -t -c $conf
echo "Success."
;;
reload)
echo -n "Reloading Nginx"
ps auxww | grep nginx | grep master | awk '{print $2}' | xargs kill -HUP
echo " done."
;;
restart)
$nginx -s reload
echo "reload done."
;;
*)
echo "Usage: $0 {start|restart|reload|stop|test|show}"
;;
esac

2. 设置文件权限并启动Nginx

命令:

1
2
3
4
sudo chkconfig --add /etc/init.d/nginx
sudo chmod 755 /etc/init.d/nginx
sudo chkconfig --add nginx
sudo service nginx start

3.设置开机启动

命令:

1
/sbin/chkconfig --level 345 nginx on

4. 其他命令介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
chkconfig --list 查看全部服务状态
例如:
运行chkconfig --list httpd
看自动启动状态
httpd 0:off 1:off 2:off 3:on 4:on 5:on 6:off
0~6是指运行级别,一般服务器都运行在3这个级别上。

添加为自动启动
chkconfig --add httpd
或者指定运行级别
chkconfig --level 345 httpd on

停止自动启动
chkconfig --del httpd
或指定运行级别
chkconfig --level 345 httpd off

参考资料:
1.nginx添加service以及随开机启动:
2.linux 命令 /sbin/chkconfig
3.nginx加入到service服务 systemctl安装nginx 自启动