Linux – auto rescue mysql server when it stop working
if you are a network administrator or you have a private web server , i think you will at least faced unexpected shutdown issue of mysql server. rumors said it happened due to lacking of system resources (RAM is the most common case). it seems that Linux will kill a process that exceeded its RAM limit – depend on system resources. you know, i have a workaround for this issue 🙂
In order for our websites to work properly again, we’ll need to restart mysql server. what you need to do is to setup a cron job to monitor server and restart mysql server if mysql is down. firstly, create rescuemysql.sh and save it
#auto process script #check for process instance and trigger restart if no instance found #author: Atheotsky #set process name PNAME="mysqld" #count processes function countProcess() { #set total of given process to global PTOTAL PTOTAL=$(ps -e | grep "$1" | wc -l) } #invoke function with param PNAME countProcess $PNAME #conditional command if [ "$PTOTAL" -eq "0" ] then #need to update PATH so cron can locate execute path for program PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin #/etc/init.d/mysql restart service mysql restart fi
next step is to setup your cron job, i add this script to root crontab because “service mysql restart” requires root privilege.
execute this command to open root crontab editor
sudo crontab -e -u root
add following line to the end of root cron file
# rescue mysqld */1 * * * * /bin/bash /path/to/your/script.sh
look a bit confusing ? take a look at this
* * * * * command to be executed ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └───── day of week (0 - 7) (0 or 7 are Sunday, or use names) │ │ │ └────────── month (1 - 12) │ │ └─────────────── day of month (1 - 31) │ └──────────────────── hour (0 - 23) └───────────────────────── min (0 - 59)
At min position, we have */1, this means your script will run every minute – don’t worry, our script is very light and only restart mysql server if it’s down.
ok, your server can rescue mysql server by itself from now on. cheer!