Categories
Linux

Monit – system monitoring and error recovery

With Monit you can monitor services and resources of your server easily.

It’s a really cool tool since it also allows you to restart a service if this one goes down, or notify you if the load or memory is getting really high.

Installing

apt-get install monit

edit vim /etc/monit/monitrc, starting from line 118 and uncomment below lines, this will enable monit and the web interface

set httpd port 2812 and
use address YOURIPHERE # only accept connection from localhost
allow 0.0.0.0/0.0.0.0  # allow anyone to connect
allow admin:monit # require user 'admin' with password 'monit'

Then execute to take affect

sudo monit reload

Now you can check the status of monit

monit status

Or access via web to http://YOURIP:2812

The you can start monitoring services and in case they are down monit will raise them again.

In my case I use serverpilot with nginx, php fpm and mysql. This goes in the same config file 😉

check process mysqld with pidfile /var/run/mysqld/mysqld.pid
    start program = "/etc/init.d/mysql start"
    stop program = "/etc/init.d/mysql stop"
if 2 restarts within 3 cycles then unmonitor

check process nginx-sp with pidfile /var/run/nginx-sp.pid
    start program = "/etc/init.d/nginx-sp start"
    stop program = "/etc/init.d/nginx-sp stop"
if 2 restarts within 3 cycles then unmonitor

check process php7.0-fpm-sp with pidfile /var/run/php7.0-fpm-sp.pid
    start program = "/etc/init.d/php7.0-fpm-sp start"
    stop program = "/etc/init.d/php7.0-fpm-sp stop"
if 2 restarts within 3 cycles then unmonitor

And lastly setup your mail server so you can get alerts:

set alert YOURMAIL@gmail.com 
set mailserver smtp.elasticemail.com port 2525
    username "user" password "passwd"

Once you have set up the configuration, check the syntax:

monit -t

After resolving any possible syntax errors, you can start running all of the monitored programs.

monit start all

Lot of this thanks to this guide.