J

Using monit for server monitoring

19 Mar 2014

Monit (as the name suggests) is a tool designed for monitoring systems, processes and filesystems. There are others out there which go far and above what Monit is capable of but with those more extravagant tools also comes more of a learning curve. Monit does an excellent job in being easy to setup and packs 95% of the requirements most developers will ever need to implement without a need to get too involved.

Installation

Monit is available within most major Linux flavours via the package manager so getting it installed can be done in a single line.

sudo apt-get install monit

or if you’re using yum

sudo yum install monit

Configuring monitoring

Depending on your Linux distribution, the configuration file will either live at ` /etc/monit/monitrc on Debian based systems or /etc/monit.conf` on RHEL/CentOS. One handy thing to note is that Monit allows this file to reside in a few different locations on the file system in case one of them are not available to you.

Monit ships with it’s own domain specific language that doesn’t require any programming experience however math operator knowledge will be beneficial should you try to create more in depth checks.

Examples of monitoring

The example below demonstrates how to implement some basic checks like checking for a process, ensuring system resources are not overrun and a simple log rotate.

# Ensuring a process (like Apache) is running
check process apache with pidfile /var/run/apache2.pid
  start program = "/etc/init.d/apache2 start" with timeout 30 seconds
  stop program  = "/etc/init.d/apache2 stop"

# Don't let CPU use over 50%
if cpu is greater than 50% for 5 cycles then restart

# Ensure the file system doesn't get over 80% full
check filesystem rootfs with path /dev/hda1
  if space usage > 80% for 5 times within 15 cycles
     then alert else if succeeded for 10 cycles then alert
  if space usage > 90% for 5 cycles then
     exec '/super/cleanup/script'

# Quick and easy log rotation
check file example.log with path /var/log/example.log
  if size > 50 MB then exec '/usr/local/bin/rotate /var/log/example.log myapp'

The full list of checks and available methods can be found at the monit documentation page.

Handy hits

  • Before reloading the configuration, be sure to run monit -t to check for any syntax/compilation errors. Reloading the configuration without checking this first main result in false positives.
  • Monit has a web UI! For those GUI lovers, Monit ships with a web UI and can be configured to be exposed on a particular port of your choosing.
  • The state of the machine can be quickly determined using monit summary.