Monit can be used to monitor your services on your VPS or dedicated server. You can use Monit to make sure php7-fpm is always running and not stopped or frozen – this is very rare, but better than sorry.
Monit will check the php7-fpm process by listening on its socket. If the socket cannot be found, Monit will restart the php7-fpm service. This way you ensure your website is running WordPress where possible and the core processes always work.
Using Monit for monitoring + automatic restart of php7-fpm service
Monit needs information to check if php7-fpm is working.
We will use php7-fpm socket and its PID file.
Finding php7-fpm or TCP socket
php7-fpm can listen on either Unix or TCP sockets. In order to find out, we use this command
grep "listen =" /etc/php/7.0/fpm/pool.d/www.conf
If you see this output then php7-fpm is using UNIX sockets
listen = /run/php/php7.0-fpm.sock
If you see this output then php7-fpm is using TCP sockets, loopback interface 127.0.0.1 on port 9000
listen = 127.0.0.1:9000
Finding the Pid php7-fpm file
Monit needs a PID file:
sudo find /run -iname php*.pid
You should see results similar to this
We now have the information we need to configure Monit to monitor php7-fpm.
Configuring Monit to monitor php7-fpm
Create Monit php7-fpm config, you can use conf-enabled folder instead of conf.d, open / etc / monit / monitrc file to check.
sudo nano /etc/monit/conf.d/php7-fpm
This is Monit php7-fpm config for UNIX sockets.
It checks the php7-fpm.pid file and if it doesn’t exist Monit will try to restart it.
Monit is also going to check that the php7-fpm Unix socket exists: /var/run/php7.0-fpm.sock
check process php7-fpm with pidfile /run/php/7.0/php7-fpm.pid start program = "/usr/sbin/service php7.0-fpm start" with timeout 60 seconds stop program = "/usr/sbin/service php7.0-fpm stop" if failed unixsocket /var/run/php7.0-fpm.sock then restart
If you are using TCP sockets this will be the Monit configuration.
Monit looks for a daemon that is listening on 127.0.0.1 on port 9000, if not found Monit will reload php7-fpm after 3 CPU cycles.
Change 127.0.0.1 to match your interface and 9000 to a different port.
check process php7-fpm with pidfile /run/php/7.0/php7-fpm.pid start program = "/usr/sbin/service php7.0-fpm start" with timeout 60 seconds stop program = "/usr/sbin/service php7.0-fpm stop" if failed host 127.0.0.1 port 9000 protocol tcp for 3 cycles then restart
Check MONIT configuration for correct syntax
sudo monit -t
You should see this message indicating that everything is OK with the syntax in MONIT.
Control file syntax OK
Then reload Monit to activate the configuration
sudo service monit reload
You can check the php7-fpm status in MONIT on port 2812 or whichever port you specified in Monit.
Now your php7-fpm service will be automatically restarted if it ever crashes.