I have a Ubuntu VPS that runs a bunch of websites powered by MySQL server at the back end. For whatever reason, the websites just kept turning down because of the crush of the MySQL service. I could scale up the server to dip in more memory or set up some sort of monitoring system to monitor and restart MySQL service when it’s down.
I took the latter route with the help of m/monit, a small open-source utility for managing and monitoring Linux systems. Monit conducts automatic maintenance and repair and can execute meaningful causal actions in error situations.
While it may sound complicated, setting it up is actually quite straightforward.
Installation
As always, update the system first to keep the system update-to-date first.
sudo apt update & sudo apt upgrade
Then, install Monit from the Ubuntu repository.
sudo apt install monit
To verify the version after the installation,
sudo monit -V
Configure the web service
The nice thing about Monit is that it comes with a web interface for monitoring and managing the configured services. The default port is on 2812 but you can change that by modifying the configuration file.
sudo nano /etc/monit/monitrc
First, change the default monitoring interval if needed.
set daemon 120
Then, to enable and change the web interface settings, uncomment or change the following lines.
set httpd port 2812 use address localhost # only accept connection from localhost allow admin:monit # required user credential
If you need to check the web interface remotely, comment out the localhost line and add the following instead.
allow ipaddress/32
Monitoring MySQL and Apache services
To monitor the MySQL service,
sudo nano /etc/monit/conf.d/mysql
and add the following lines:
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
To monitor the Apache service,
sudo nano /etc/monit/conf.d/apache
and add the following lines:
check process apache2 with pidfile /run/apache2/apache2.pid
start program = "/bin/systemctl start apache2.service" with timeout 15 seconds
stop program = "/bin/systemctl stop apache2.service"
restart program = "/bin/systemctl restart apache2.service"
Now, reload the Monit service,
sudo service monit reload
And check the web interface now.