Top.Mail.Ru

Using Monit to monitor and automatically restart the MySQL service

If you need to install Monit on Ubuntu or Debian, then follow this article. For other operating systems, installation and configuration may vary.

Using Monit for monitoring + automatic restart of MySQL service

First of all, Monit needs to choose how we will check if MySQL is working.

In this article we will use a MariaDB or MySQL socket and its pid file, but this is not the only way.


Searching for a MySQL Unix or TCP socket

MySQL can listen to both unix sockets and TCP sockets. To find out, use following command:

grep "socket" /etc/mysql/my.cnf

If you received in response:

listen = /var/run/mysqld/mysqld.sock

then MySQL uses unix sockets

We will also need to find the MySQL pid. It can be found with the following command:

sudo find /run -iname mysql*.pid

You should see something similar to this output:

/run/mysqld/mysqld.pid

Thus, we have collected all the information necessary to configure Monit for MySQL monitoring.

Setting up Monit for monitoring MySQL, MariaDB, Percona

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

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

This MySQL Monit configuration is designed 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 that the Monit configuration has a valid syntax

sudo monit -t

You should see this message indicating that the Monit syntax is ok.

Control file syntax OK

Then restart Monit to activate the configuration

sudo service monit reload

You can check your MySQL Monit status on port 2812 or some other port that you specified Monit should work on.

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

Published on: 18-07-2021, 17:06