Udit Chugh Udit Chugh - 5 months ago 10
Bash Question

Can we write a script to restart MySQL every time the website is down?

I am using a Linux server hosted on AWS and due to less amount of RAM available the website goes down and I get a "Error establishing connection to database" error.

I have to restart MySQL everytime this happens.

Can we automate this process?

The command I use to restart the LAMPP server is:

sudo /opt/lampp/lampp restart

Answer

Use a bash script to monitor the mysql port and restart it if it is down

Just to demo how it works

The nc command checks that port 3306 (mysql port) is contactable If it is then $? is set to zero, so this counts as "up" otherwise $? is down. You may wish to use a different command instead of "nc", for example echo "select 1;" | mysql to attempt to run a do nothing mysql command

while [ 1 ]
  do sleep 1
  nc -z localhost 3306
  if [ $? == 0 ]; then echo "up"
  else echo "down"
  fi
done

The actual version you might use could look like this

while [ 1 ]
  do sleep 10
  nc -vz localhost 3306
  if [ $? != 0 ]; then /opt/lampp/lampp restart
  fi
done

You can leave a window open (maybe using the "screens" command too) and run this 24x7

If you can increase the time interval to 1 minute then it would be ok to run out of cron like this

in crontab ( to run every minute)

* * * * * /path/to/script

script

#!/bin/bash
  nc -vz localhost 3306 > /dev/null 2>&1 
  if [ $? != 0 ]; then /opt/lampp/lampp restart
  fi
Comments