Monit can be used to monitor your services on your VPS or dedicated server. You can use Monit to make sure nginx is always running in case it halts or freezes up – note this is very rare but it is better to be safe than sorry.
Monit will check which port nginx is running on and restart the nginx service in case it cannot be detected. This way you ensure your web site, perhaps running WordPress, is always running. Cloudways employs this monitoring technique with Monit on all of its managed VPS.
If you need to install Monit on Ubuntu or Debian then follow this guide.
Use Monit to Monitor + Restart nginx Service Automatically
The easiest way is to find out which port nginx is running on is to run netstat.
sudo netstat -plnt
Look for the nginx entry under the PID/Program name, the Local Address column will show which port nginx is using.
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:143 0.0.0.0:* LISTEN 26511/dovecot tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1835/varnishd tcp 0 0 0.0.0.0:10000 0.0.0.0:* LISTEN 22482/perl tcp 0 0 127.0.0.1:465 0.0.0.0:* LISTEN 6600/master tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 6600/master tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 22836/nginx tcp 0 0 0.0.0.0:2812 0.0.0.0:* LISTEN 26782/monit tcp 0 0 127.0.0.1:6082 0.0.0.0:* LISTEN 6000/varnishd tcp 0 0 0.0.0.0:69 0.0.0.0:* LISTEN 15154/sshd tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 15947/mysqld tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 22086/redis-server tcp 0 0 127.0.0.1:587 0.0.0.0:* LISTEN 6600/master
Use Monit to Monitor nginx
Create a Monit nginx configuration
sudo nano /etc/monit/conf.d/nginx
Paste the Monit nginx configuration.
It checks for the nginx.pid file and if it doesn’t exist Monit will try to restart it.
Monit looks for a daemon listening on port 80, if not found Monit will restart nginx after 3 CPU cycles.
If you are using https (SSL) then you should change port 80 to 443.
check process nginx with pidfile /run/nginx.pid start program = "/usr/sbin/service nginx start" with timeout 60 seconds stop program = "/usr/sbin/service nginx stop" if failed host 127.0.0.1 port 80 protocol http for 3 cycles then restart
Check the Monit configuration has valid syntax
sudo monit -t
You should see this message indicating the Monit syntax is OK.
Control file syntax OK
Then reload Monit to activate the configuration
sudo service monit reload
You can check your nginx Monit status on port 2812 or whichever port you have specified Monit should run on.
If you want email alerts from Monit via Mailgun alerts follow this guide.
Now your nginx service will automatically restart if it ever fails.