Monitoring Nginx and PHP-FPM on Ubuntu 14.04 and Restart the Services on Failure

Hi,

Running Nginx and php-fpm on an Ubuntu server is a good choice if you have a low specs VPS, Nginx is lighter than Apache, I think. 🙂

To monitor Nginx and php-fpm to keep it running all the time, I used to use Monit. Monit is a small program that runs as a service that serves to monitor a particular service as well restart it when the service is down.

How to install and configure Monit to monitor Nginx and php-fpm while you sleep like a top.

$sudo apt-get install monit

$sudo nano /etc/monit/monitrc

Uncomment these lines

set httpd port 2812 and
use address localhost
allow localhost

Create file /etc/monit/conf.d/nginx.conf with these lines

check process nginx with pidfile /var/run/nginx.pid
group www-data
start program = "/etc/init.d/nginx start"
stop program = "/etc/init.d/nginx stop"
if cpu is greater than 50% for 2 cycles then alert
if failed host 127.0.0.1 port 80 protocol http then restart
if 5 restarts with 5 cycles then timeout

Then create file /etc/monit/conf.d/php5-fpm.conf with these lines

check process php5-fpm with pidfile /var/run/php5-fpm.pid
group www-data
start program "/etc/init.d/php5-fpm start"
stop program "/etc/init.d/php5-fpm stop"
if failed unixsocket /var/run/php5-fpm.sock then restart
if 5 restarts within 5 cycles then timeout

$sudo service monit restart

$sudo monit status

The Monit daemon 5.6 uptime: 0m

Process ‘nginx’
status Running
monitoring status Monitored
pid 1707
parent pid 1
uptime 18m
children 4
memory kilobytes 1024
memory kilobytes total 6784
memory percent 0.0%
memory percent total 0.4%
cpu percent 0.0%
cpu percent total 0.0%
port response time 0.005s to 127.0.0.1:80 [HTTP via TCP]
data collected Mon, 21 Sep 2015 00:45:57

Process ‘php5-fpm’
status Running
monitoring status Monitored
pid 1215
parent pid 1
uptime 18m
children 2
memory kilobytes 12912
memory kilobytes total 19600
memory percent 0.7%
memory percent total 1.1%
cpu percent 0.0%
cpu percent total 0.0%
unix socket response time 0.000s to /var/run/php5-fpm.sock [DEFAULT]
data collected Mon, 21 Sep 2015 00:45:57

System 'tfq-X401U'
status Running
monitoring status Monitored
load average [0.84] [0.85] [0.71]
cpu 0.0%us 0.0%sy 0.0%wa
memory usage 545576 kB [32.9%]
swap usage 0 kB [0.0%]
data collected Mon, 21 Sep 2015 00:45:57

Reference: http://www.patlathem.com/automatic-service-restarts-on-failure-with-monit/