How to install and use Monit on Ubuntu/Debian Linux server as process supervision tool

Posted on in Categories , , , last updated June 25, 2017

How do I install and configure monit to restart services such as Nginx/Apache/OpenVPN server when failed on Debian or Ubuntu Linux?

Monit is a free and open source software that acts as process supervision. It comes with the ability to restart services which have failed. You can use Systemd, daemontools or any other such tool for the same purpose. This tutorial shows how to install and configure monit as Process supervision on Debian or Ubuntu Linux.

What is the purpose of monit?

From the home page:

Monit is a small Open Source utility for managing and monitoring Unix systems. Monit conducts automatic maintenance and repair and can execute meaningful causal actions in error situations. With all features needed for system monitoring and error recovery. It’s like having a watchdog with a toolbox on your server. Monitor network connections to various servers, either on localhost or on remote hosts. TCP, UDP and Unix Domain Sockets are supported. Network tests can be performed on a protocol level; Monit has built-in tests for the main Internet protocols, such as HTTP, SMTP etc. Monit can act if an error situation should occur, e.g.; if sendmail is not running, Monit can start sendmail again automatically or if apache is using too much resources (e.g. if a DoS attack is in progress) Monit can stop or restart apache and send you an alert message.

Installing monit

Type the following apt-get command/apt command:
$ sudo apt-get install monit
Sample outputs:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  sysvinit-core
The following NEW packages will be installed:
  monit
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 273 kB of archives.
After this operation, 826 kB of additional disk space will be used.
Get:1 http://mirrors.digitalocean.com/ubuntu xenial/universe amd64 monit amd64 1:5.16-2 [273 kB]
Fetched 273 kB in 0s (733 kB/s)
Selecting previously unselected package monit.
(Reading database ... 144487 files and directories currently installed.)
Preparing to unpack .../monit_1%3a5.16-2_amd64.deb ...
Unpacking monit (1:5.16-2) ...
Processing triggers for systemd (229-4ubuntu17) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up monit (1:5.16-2) ...
Processing triggers for systemd (229-4ubuntu17) ...
Processing triggers for ureadahead (0.100.0-19) ...

How do I enable monit service at boot time?

Type the following command:
$ sudo systemctl enable monit

How do I start/stop/restart monit service?

The syntax is:
$ sudo systemctl status monit
$ sudo systemctl stop monit
$ sudo systemctl restart monit
$ sudo systemctl start monit

Configuring monit

You need to edit the following files:

  1. Main config file : /etc/monit/monitrc
  2. Directories for process/server specific files : /etc/monit/conf-available/ and /etc/monit/conf-enabled/

Let us edit out /etc/monit/monitrc using a text editor such as vim command or nano command:
$ sudo vi /etc/monit/monitrc
OR
$ sudo nano /etc/monit/monitrc
First set alert recipients email address (your Linux box must be configured to route email. See how to use gmail account to relay email from a shell prompt or Postfix as smarthost using an external smptd/cloud email service):
set alert admin@your-domain-name-here
It is possible to get only security releated alert using the following syntax:
set alert security@your-domain-name-here on { checksum, permission, uid, gid }
Please note that monit by default sends just one email notification if a service failed and another when/if it recovers. For example if you want to be notified each fifth cycle if a service remains in a failed state, you can use:
alert vivek@server1.cyberciti.biz with reminder on 5 cycles
Enable an embedded HTTP interface which can be used to view status of services monitored and manage services from a web interface:

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

Save and close the file.

How do I configure monit for monitoring my own process named foo?

Create a file called /etc/monit/conf-available/foo:
$ sudo vi /etc/monit/conf-available/foo
Append the following config:

check process foo
        matching "foo"
        start program = "/etc/init.d/foo start"
        stop program = "/usr/bin/killall foo"

Save and close the file. Enable it:
$ sudo ln -s /etc/monit/conf-available/foo /etc/monit/conf-enabled/
Check and run syntax check for the monit control/config file:
$ monit -t
Control file syntax OK

Reload monit, run:
$ sudo /etc/init.d/monit reload
OR
$ sudo systemctl reload monit

How do I configure monit for OpenVPN server?

OpenVPN is a free and open source VPN server for Linux and Unix-like systems. Make sure OpenVPN starts when it dies for any reason:
$ sudo vi /etc/monit/conf-available/openvpn
Append the following config:

 check process openvpn  with pidfile /var/run/openvpn/server.pid
   group nogroup
   start program = "/etc/init.d/openvpn start"
   stop  program = "/etc/init.d/openvpn stop"
   if failed host localhost port 1194 then restart
   if 5 restarts with 5 cycles then timeout
   depend on openvpn_bin
 
 check file openvpn_bin with path /usr/sbin/openvpn
   group nogroup
   include /etc/monit/templates/rootbin

Save and close the file. Enable it:
$ sudo ln -s /etc/monit/conf-available/openvpn /etc/monit/conf-enabled/
Check and run syntax check for the monit control/config file:
$ monit -t
Control file syntax OK

Reload monit, run:
$ sudo /etc/init.d/monit reload
OR
$ sudo systemctl reload monit

How do I configure monit for monitoring MariaDB/MySQL server?

$ cat /etc/monit/conf-available/mysql
Sample outputs:

 check process mysqld with pidfile /var/run/mysqld/mysqld.pid
   group database
   group mysql
   start program = "/etc/init.d/mysql start"
   stop  program = "/etc/init.d/mysql stop"
   if failed host localhost port 3306 protocol mysql with timeout 15 seconds for 3 times within 4 cycles then restart
   if failed unixsocket /var/run/mysqld/mysqld.sock protocol mysql for 3 times within 4 cycles then restart
   if 5 restarts with 5 cycles then timeout
   depend mysql_bin
   depend mysql_rc
 
 check file mysql_bin with path /usr/sbin/mysqld
   group mysql
   include /etc/monit/templates/rootbin
 
 check file mysql_rc with path /etc/init.d/mysql
   group mysql
   include /etc/monit/templates/rootbin

How do I configure monit for Nginx server?

$ cat /etc/monit/conf-available/nginx
Sample outputs:

 check process nginx with pidfile /var/run/nginx.pid
   group www
   group nginx
   start program = "/etc/init.d/nginx start"
   stop program = "/etc/init.d/nginx stop"
   if 5 restarts with 5 cycles then timeout
   depend nginx_bin
   depend nginx_rc

 check file nginx_bin with path /usr/sbin/nginx
   group nginx
   include /etc/monit/templates/rootbin

 check file nginx_rc with path /etc/init.d/nginx
   group nginx
   include /etc/monit/templates/rootbin

How do I configure monit for Apache server?

$ cat /etc/monit/conf-available/apache2
Sample outputs:

 check process apache with pidfile /var/run/apache2/apache2.pid
   group www
   group apache
   start program = "/etc/init.d/apache2 start"
   stop program  = "/etc/init.d/apache2 stop"
   if 4 restarts within 20 cycles then timeout
   if failed host localhost port 80 with protocol http and request "/server-status" with timeout 25 seconds for 4 times within 5 cycles then restart
   depend apache_bin
   depend apache_rc
 
 check file apache_bin with path /usr/sbin/apache2
   group apache
   include /etc/monit/templates/rootbin
 
 check file apache_rc with path /etc/init.d/apache2
   group apache
   include /etc/monit/templates/rootbin

How do I configure monit for OpenSSH SSHD server?

$ cat /etc/monit/conf-available/openssh-server
Sample config:

 check process sshd with pidfile /var/run/sshd.pid
   group system
   group sshd
   start program = "/etc/init.d/ssh start"
   stop  program = "/etc/init.d/ssh stop"
   if failed host localhost port 22 with proto ssh then restart
   if 5 restarts with 5 cycles then timeout
   depend on sshd_bin
   depend on sftp_bin
   depend on sshd_rc
   depend on sshd_rsa_key
   depend on sshd_dsa_key
 
 check file sshd_bin with path /usr/sbin/sshd
   group sshd
   include /etc/monit/templates/rootbin
 
 check file sftp_bin with path /usr/lib/openssh/sftp-server
   group sshd
   include /etc/monit/templates/rootbin
 
 check file sshd_rsa_key with path /etc/ssh/ssh_host_rsa_key
   group sshd
   include /etc/monit/templates/rootstrict
 
 check file sshd_dsa_key with path /etc/ssh/ssh_host_dsa_key
   group sshd
   include /etc/monit/templates/rootstrict
 
 check file sshd_rc with path /etc/ssh/sshd_config
   group sshd
   include /etc/monit/templates/rootrc

Remember you must use the ln command to link those files and reload monit server
$ cd /etc/monit/conf-enabled/
$ sudo ln -s /etc/monit/conf-available/openssh-server
$ sudo ln -s /etc/monit/conf-available/nginx
$ sudo ln -s /etc/monit/conf-available/mysql
$ sudo ln -s /etc/monit/conf-available/apache2
$ sudo monit -t
$ sudo /etc/init.d/monit reload

How do I view monit info from the CLI?

Run the following command to see a quick summary of monit:
$ sudo monit summary
Sample outputs:

The Monit daemon 5.16 uptime: 1h 9m 

Process 'openvpn'                   Running
File 'openvpn_bin'                  Accessible
System 'blr-nixcraft-do-0001'       Running

To see status of monit run:
$ sudo monit status
Sample outputs:

Fig.02: Print service status information.

To see detailed info about openvpn process only:
$ sudo monit status openvpn
Sample outputs:

The Monit daemon 5.16 uptime: 1h 15m 

Process 'openvpn'
  status                            Running
  monitoring status                 Monitored
  pid                               31577
  parent pid                        1
  uid                               65534
  effective uid                     65534
  gid                               65534
  uptime                            1h 17m 
  threads                           1
  children                          0
  memory                            6.1 MB
  memory total                      6.1 MB
  memory percent                    1.3%
  memory percent total              1.3%
  cpu percent                       0.0%
  cpu percent total                 0.0%
  port response time                2.091 ms to [localhost]:443 type TCP/IP protocol DEFAULT
  data collected                    Sun, 25 Jun 2017 00:12:40

How do I view monit log files?

You can use the tail command as follows:
$ sudo tail -f /var/log/monit.log
Sample outputs:

[IST Jun 24 23:54:40] info     : Starting Monit HTTP server at [localhost]:2812
[IST Jun 24 23:54:40] info     : Monit HTTP server started
[IST Jun 24 23:54:40] info     : 'blr-nixcraft-do-0001' Monit reloaded

Or use the grep command as follows to search something in a log file:
$ grep foo /var/log/monit.log
$ grep sshd /var/log/monit.log
$ grep openvpn /var/log/monit.log

Sample outputs:

[IST Jun 24 22:55:28] info     : 'openvpn' start: /etc/init.d/openvpn

To see and control monit from a web browser type your server url in browser (provided that you configured set http as described above):
http://server1.cyberciti.biz:2812

Fig.02: Monit service manager in action
Fig.02: Monit service manager in action

You can click on service such as OpenVPN to view its status or start/stop/restart from a web browser itself:
Fig.03: OpenVPN service managed by monit
Fig.03: OpenVPN service managed by monit

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment