How to restart the database “Error Establishing a Database Connection”?

If the database connection error does not happen everyday you can set up a cron job that will restart the database for you.

I have this problem on a DigitalOcean droplet, so this is how I solved it:

  1. Create the bash file in /var/www/mysql.sh (make sure to be a private path, not a public file)
  2. cd/var/www/
  3. touch mysql.sh
  4. pico mysql.sh
#!/bin/bash
UP=$(/etc/init.d/mysql status | grep running | grep -v not | wc -l);
if [ "$UP" -ne 1 ];
then
        echo "MySQL is down.";
        sudo service mysql start
else
        echo "All is well.";
fi

Add file permission:

chmod +x /var/www/mysql.sh

Login as root

sudo su

Edit cronjobs

crontab -l (to see current cron jobs)

crontab -u root -e

Add this line (will trigger every 1 minute):

*/1 * * * * /var/www/mysql.sh > /var/www/cron.log 2>&1

Enable and restart cronjob

sudo systemctl enable cron
sudo systemctl restart cron

Check the logs to make sure everything is fine:

pico /var/www/cron.log

How to restart the database “Error Establishing a Database Connection”?