Nginx配置成CentOS服务
前言
源码编译安装Nginx后,需要配置开机自启,顺便想要通过服务化进行操作nginx的运行,因此编写了本教程记录个人的解决过程。
https://blog.csdn.net/RisenMyth/article/details/104589071
编写Shell脚本
这里的NGINX_PATH
变量请填写自己的nginx可执行文件路径。
#!/bin/sh
# nginx
# chkconfig: 2345 55 25
# description: nginx service shell.
NGINX_PATH=/opt/nginx/sbin/nginx
SERVER_PID=""
checkPid() {
SERVER_PID=$(ps -ef | grep nginx | grep master | grep -v grep | awk '{ print $2 }')
}
startNginx() {
checkPid
if [ -n "$SERVER_PID" ]; then
echo "Nginx is running."
else
echo "Nginx starting..."
$NGINX_PATH
echo "Nginx started successfully."
fi
}
stopNginx() {
checkPid
if [ -n "$SERVER_PID" ]; then
echo "Nginx stopping..."
$NGINX_PATH -s quit
waitStop
echo "Nginx stopped successfully."
else
echo "Nginx has stopped."
fi
}
waitStop() {
while [ -n "$SERVER_PID" ]
do
sleep 1
checkPid
done
}
restartNginx() {
checkPid
if [ -n "$SERVER_PID" ]; then
stopNginx
fi
waitStop
startNginx
}
statusNginx() {
checkPid
if [ -n "$SERVER_PID" ]; then
echo "Nginx stauts: Running."
else
echo "Nginx stauts: Stopped."
fi
}
reloadNginx() {
checkPid
if [ -n "$SERVER_PID" ]; then
$NGINX_PATH -s reload
else
echo "Nginx needs to be running before it can be reloaded."
fi
}
case "$1" in
"start")
startNginx
;;
"stop")
stopNginx
;;
"reload")
reloadNginx
;;
"restart")
restartNginx
;;
"status")
statusNginx
;;
*)
echo "Support parameter list on (start|stop|reload|restart|status)."
;;
esac
将该脚本添加到服务
将以上脚本复制到/etc/init.d
目录下,命名为nginx
,并授予可执行权限:
chmod a+x nginx
添加到服务:
chkconfig --add nginx
结束
至此,你就可以通过service nginx (start|stop|reload|restart|status)
命令去查看与操作nginx了,如果你想要可以开机自启nginx,则可以执行以下命令:
chkconfig nginx on
教程结束,祝你们成功。