Monit can be used to monitor your services on your VPS or dedicated server. You can use Monit to make sure MySQL (MariaDB, Percona etc) is always running in case it crashes because of bots brute forcing or it runs out of resources.
Monit will check the MySQL process by looking at the unix socket it is listening on. If the socket cannot be detected Monit will restart the MySQL service. This way you ensure your web site, perhaps running WordPress, is always running essential processes. Cloudways uses this monitoring technique with Monit on all of its managed VPS.
If you need to install Monit on Ubuntu or Debian then follow this guide.
Use Monit to Monitor + Restart MySQL Service Automatically
Monit needs some information to check to see if MySQL is healthy.
We will use the socket MariaDB or MySQL is using and its pid file.
Find MySQL Unix or TCP Socket
MySQL can listen on both unix sockets and TCP sockets. To find out use this command
grep "socket" /etc/mysql/my.cnf
If you see this output then MySQL is using unix sockets
listen = /var/run/mysqld/mysqld.sock
Find MySQL pid file
Monit needs the pid file as well
sudo find /run -iname mysql*.pid
You should see some output like this
Now we have the information necessary to configure Monit for MySQL monitoring.
Configure Monit to Monitor MySQL, MariaDB, Percona
Create a Monit MySQL configuration, you may use the
conf-enabled folder instead of
conf.d, check your
/etc/monit/monitrc file to verify.
sudo nano /etc/monit/conf.d/mysql
This Monit MySQL configuration is for unix sockets.
It checks for the
mysqld.pid file and if it doesn't exist Monit will try to restart it.
Monit is also going to check that the MySQL unix socket exists:
check process mysql with pidfile /run/mysqld/mysqld.pid start program = "/usr/sbin/service mysql start" with timeout 60 seconds stop program = "/usr/sbin/service mysql stop" if failed unixsocket /var/run/mysqld/mysqld.sock then restart
Check the Monit configuration has valid syntax
sudo monit -t
You should see this message indicating the Monit syntax is OK.
Control file syntax OK
Then reload Monit to activate the configuration
sudo service monit reload
You can check your MySQL Monit status on port 2812 or whichever port you have specified Monit should run on.
Now your MySQL service will automatically restart if it ever fails.