Home >Backend Development >PHP Tutorial >PHP script monitors Nginx 502 errors and automatically restarts php-fpm_PHP tutorial
This article mainly introduces PHP scripts to monitor Nginx 502 errors and automatically restarts php-fpm. This article directly explains Implement the code and then put it into cron for execution. Friends who need it can refer to it
Recently, Nginx 502 Bad Gateway appears on the server from time to time. It is fine if it is next to the computer. But what should I do if it is in the middle of the night or when I go out?
It doesn’t matter. Write a script to detect the service status. If any exception is found, it will automatically restart.
Automatic restart script:
The code is as follows:
$url = 'http://blog.rebill.info';
$cmd = '/usr/local/php/sbin/php-fpm restart';
for($i = 0; $i < 5; $i ){
$exec = "curl connect-timeout 3 -I $url 2>/dev/null";
$res = shell_exec($exec);
if(stripos($res, '502 Bad Gateway') !== false){
shell_exec($cmd);
exit();
}
}
The principle is to use curl to obtain the HTTP header, and when the 502 status code is found, execute the command to restart php-fpm.
Change the url and cmd to your own according to the actual situation. Then put it in crontab and execute it once a minute.
The code is as follows:
*/1 * * * * /usr/bin/php /root/crontab/nginx502.php
Done!