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

Views: 1085

 

I love MySql and I love it even more on Nano Servers, but it doesn’t like them. I bit too much work or a tiny DDOS attack brings down the database.

I hope to implement the following 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 24×7

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

 

Source: shell – Can we write a script to restart MySQL every time the website is down? – Stack Overflow

Leave a Reply