PHP Script to monitor Apache/php-fpm
I moved a web site to new dedicated server. But for some reason, php-fpm crashed. I increased the max_children settings, but it happend again. I do not want down time while i am investigating the problem. So i created a PHP script, that will check if site is working or not.
Script have 2 part.
health-check.php
1 |
<?php $id = (int) $_GET["sok"]; echo $id; |
It is simple PHP script, that get a param and print it.
This file is placed on root of your web site, so it can be accessed using URL http://yoursite/health-check.php
monitor-server.php
Create
1 2 |
mkdir /usr/serverok/ vi /usr/serverok/monitor-server.php |
Add following content
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $myNumber = rand(1,100); $monitorUrl = "https://YOUR_DOMAIN_HERE/health-check.php?sok=" . $myNumber; $ch = curl_init($monitorUrl); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_TIMEOUT,4); $output = curl_exec($ch); curl_close($ch); if ($output != $myNumber) { $cmd = "systemctl restart apache2"; exec($cmd); $cmd = "systemctl restart php7.2-fpm"; exec($cmd); $timeStamp = date("Y-m-d H:i:s"); error_log("$timeStamp restarted", 3, "/var/log/sok-monitor.log"); } |
On the script, replace YOUR_DOMAIN_HERE with your actual domain name.
systemctl restart apache2 is for restart apache web server. If you use nginx, replace it. systemctl restart php7.2-fpm restart php-fpm, if you have differnt version of php, you need to change it.
The script is generate a random number, pass it to health-check.php script. Compared the value returned with generated random number to make sure the value is correct. If web server or php-fpm fail, this check will fail.
Now set a cronjob
1 |
crontab -e |
Add
1 |
*/5 * * * * /usr/bin/php /usr/serverok/monitor-server.php |
Related Posts