Sometimes you need to have a third-eye to help you monitor the service on your server. One of my favorite tools to help me monitor and automatically restart service is using Monit.

Here’s how to install and setup Monit for monitoring and restart Nginx service automatically on your server.

Install monit on ubuntu

#apt update && apt install monit

Make sure Monit is autostart

#systemctl enable monit && systemctl start monit

Configure monit service with value below, adjust as you need

#vi /etc/monit/monitrc
set daemon 120 # check services at 2-minute intervals
set log /var/log/monit.log
set pidfile /var/run/monit.pid
set idfile /var/lib/monit/id
set statefile /var/lib/monit/state
set eventqueue
basedir /var/lib/monit/events # set the base directory where events will be stored
slots 100 # optionally limit the queue size
set httpd port 2812 and
allow localhost
allow user:pass
include /etc/monit/conf.d/*
include /etc/monit/conf-enabled/*

The configuration will look like below

Monitrc configuration

There is already provided configuration file for which service you will monitor.

Available service monit configuration

Let’s create symlink to enable nginx monitoring

#ln -s /etc/monit/conf-available/nginx /etc/monit/conf-enable/

For distros with systemd you may need to adjust some of the Nginx configuration.
The default installed configuration available will look like

Monit-Nginx default configuration

Since i am using Ubuntu 20 with systemd, heres my configuration value

#cat /etc/monit/conf-available/nginx
check process nginx with pidfile /var/run/nginx.pid
group www
group nginx
start program = "/usr/bin/systemctl start nginx"
stop program = "/usr/bin/systemctl stop nginx"
if failed host localhost port 80 protocol http for 3 cycles then restart
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

Check monit configuration and if all is ok, enable the nginx monit check.

#monit -t && systemctl reload monit
#monit monitor nginx && monit start nginx
#monit status nginx

Here’s the Nginx status monitor by Monit

Nginx Monit Status

Hope this help you.
Thanks

Previous ArticleNext Article

Leave a Reply

Your email address will not be published. Required fields are marked *