Nginx配置成CentOS服务

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

教程结束,祝你们成功。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值