Using Monit for monitoring + automatic restart of MySQL service

Monit can be used to monitor your services on your VPS or dedicated server. You can use Monit to ensure that MySQL (MariaDB, Percona, etc.) always works in the event of a crash due to brute force attacks by bots or when resources run out.

Monit will check the MySQL process by looking at the unix socket it is listening on. If the socket cannot be found, Monit will restart the MySQL service. This way, you ensure that your website, possibly powered by WordPress, is always running the necessary processes.

If you need to install Monit on Ubuntu or Debian then follow this tutorial.

Using Monit for monitoring + automatic restart of MySQL service

Monit needs information to check if MySQL is running.

We will use a MariaDB or MySQL socket and its pid file.

Finding a 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

Finding the MySQL pid file

Monit also needs a pid file

sudo find /run -iname mysql*.pid

You should see output like this

/run/mysqld/mysqld.pid

We now have the information we need to set up Monit to monitor MySQL.

Configuring Monit for monitoring MySQL, MariaDB, Percona

Create Monit MySQL config file, you can use folder conf-enabled instead conf.d to check / etc / monit / monitrc.

sudo nano /etc/monit/conf.d/mysql

This Monit MySQL configuration is for unix sockets.

It will check the mysqld.pid file and if it doesn’t exist Monit will try to restart it.

Monit will also check the MySQL socket: /var/run/mysqld/mysqld.sock

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 that the Monit syntax is fine.

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 pointed Monit to should work.

Now your MySQL service will be automatically reloaded if it ever fails.

Sidebar