zjhui
zjhui

Reputation: 809

Shell script to start the nginx when it quit unexpectly

Centos 6.0), and i find that my nginx will quit unexpectedly. So i want to write a shell script to start the nginx when it quit . Below is the script:

 #!/bin/bash
 nginxBin=/usr/bin/nginx
 confFile=/etc/nginx/nginx.conf
 LOGS=/var/log/nginx/nginx.log
 restart_nginx() {
     echo " `date`---restart the nginx " >> $LOGS
     $nginxBin -c $confFile
  }

 while true
 do
     NGINX_NUM=`ps aux | grep "nginx" | grep -v "grep" | wc -l`
     if [ $NGINX_NUM -lt 2 ]; then
         restart_nginx
         continue
     fi                                                                                                                                                                                                 
     sleep 5
 done

And i put this in /etc/rc.local , but it when i kill the nginx for a test , it seems didn't work. For i'm not familiar with shell script .
Can anyone help me ? Thank you~~

zjhui

Upvotes: 0

Views: 1434

Answers (2)

Stephane Rouberol
Stephane Rouberol

Reputation: 4384

Why don't you use an init script fitting to your CentOS distribution?

An example can be read here: http://articles.slicehost.com/2009/2/2/centos-adding-an-nginx-init-script

Upvotes: 0

tripleee
tripleee

Reputation: 189679

If your script's name includes the string nginx, it will commit suicide after 5 seconds.

If you have pidof, try with pidof nginx instead if the awkward double grep. Otherwise, try to tighten up your regex.

For the record, the customary way to avoid having grep return itself in a ps listing is to use a regex which doesn't match itself. For example, ps aux | grep -c '[n]ginx'. The -c gets rid of the wc -l. Maybe add a word boundary and/or anchors to avoid killing your own script (assuming it's called something like respawn-nginxen).

Upvotes: 1

Related Questions