将 nginx 做成服务并开机启动
1.制作启停脚本
脚本例子,可以根据需求对应修改(PS: 脚本无 sh 后缀)
#!/bin/bash
#chkconfig: 2345 80 90
#description:nginx
#nginx程序路径
nginxd=/data/nginx
#nginx配置文件路径
nginx_config=/data/nginx/conf/nginx.conf
#nginx pid文件的路径,可以在nginx的配置文件中找到
nginx_pid=/data/nginx/logs/nginx.pid
start() {
if [ -e $nginx_pid ];then
echo "nginx already running...."
exit 1
fi
echo -n $"Starting $prog: "
$nginxd/sbin/nginx -c ${nginx_config}
}
# Stop nginx daemons functions.
stop() {
echo -n $"Stopping $prog: "
$nginxd/sbin/nginx -s stop
}
# reload nginx service functions.
reload() {
echo -n $"Reloading $prog: "
$nginxd/sbin/nginx -s reload
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;
status)
c_pid=`ps -ef |grep /data/nginx | grep -v 'grep' | awk 'NR==1{print $2}'`
echo $c_pid
if [ "$c_pid" = "" ] ; then
echo "Stopped"
exit 3
else
echo "Running $c_pid"
exit 0
fi
;;
*)
echo $"Usage: $prog {start|stop|restart|reload|status}"
exit 1
esac
exit 0
2.软连接
在
/etc/init.d生成对应的软连接,
ln -s 目标 快捷方式目录`
ln -s /data/nginx/nginx /etc/init.d/nginx
这样就可以直接使用命令
service nginx {start|stop|restart|reload|status}
3.开机自启动
方式一:
// 添加到开机列表里面
chkconfig --add nginx
// 查看列表
chkconfig --list
// nginx服务开机自启动 off 关闭
chkconfig nginx on
服务不支持 chkconfig
#!/bin/bash
#chkconfig: 2345 80 90
#description:nginx
第一行,告诉系统使用的shell,所以的shell脚本都是这样。
第 二行,chkconfig 后面有三个参数 2345 80 90 告诉 chkconfig 程序,需要在 rc2.d~rc5.d 目录下,创建名字为 S80nginx的文件连接,连接到 /etc/rc.d/init.d 目录下的的 nginx 脚本。第一个字符是 S,系统在启动的时候,运行脚 本 nginx,就会添加一个 start 参数,告诉脚本,现在是启动模式。同时在 rc0.d 和 rc6.d 目录下,创建名字为 K90nginx 的 文件连接,第一个字符为 K,个系统在关闭系统的时候,会运行 nginx,添加一个 stop,告诉脚本,现在是关闭模式。 注意上面的三行是中,地二,第三行是必须的,否则在运行 chkconfig --add nginx 时,会报错
方式二:
直接编辑文件 /etc/rc.local
,里面直接编辑执行命令。如果没有这个文件,创建并且赋权即可。
vi /etc/rc.local
然后把所需要开机自启的服务加载到最后面,例如加载 nginx 服务开机自启:
service nginx start
这样我们就能把服务设置为开机启动,启动的命令处理启动服务外,还能把需要的脚本加载到rc.local,实现开机自动执行脚本。