Bash script to automatically restart MySQL when website database connection is down
I've been noticing that periodically my MySQL service will hang and require a restart. It's easy enough to SSH in and restart it, but I only catch it after the fact. So I wrote this little script which curls my website, sees that it's down and restarts MySQL and shoots me an email with sSMTP. This only checks for the MySQL service not accepting connections from Apache. If there's an error with Apache, or it's not running this won't do anything.
#!/bin/bash #Downloads index to specified file, use wget if you don't care what it's named. curl --silent -o /scripts/temp/index.txt https://robbiecrash.me -k #Silently diff the downloaded file with a copy of Apache's default 'can't #connect to database' html page and execute actions if they match if diff /scripts/temp/index.txt /scripts/___NoDB.txt -q > /dev/null then # Restarting would bung up the script if it wasn't running /usr/sbin/service mysql start # restart incase it was already running but hung /usr/sbin/service mysql restart # Add the date to a log file date >> /var/log/sqlService.log # Create and mail temporary copy of the message with date cat /scripts/checkSQL.msg > /scripts/temp/checkSQL.msg date >> /scripts/temp/checkSQL.msg /usr/sbin/ssmtp MYEEMAILADDRESS < /scripts/temp/checkSQL.msg fi rm /scripts/temp/index.txt rm /scripts/temp/checkSQL.msg
The file checkSQL.msg is just a normal ssmtp message file like so:
To: MYEEMAILADDRESS From: MYEEMAILADDRESS Subject: Database unreachable The database failed a connection attempt and the mysql service was automatically restarted on: