Nginx 502 Bad Gateway appears on the server from time to time recently. It’s fine if it’s next to the computer, but in the middle of the night or What should I do if I go out?
It doesn't matter, write a script to detect the service status, find any abnormalities, and automatically restart.
Automatic restart script:
Copy code 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.
Copy code The code is as follows:
*/1 * * * * /usr/bin/php /root/crontab/nginx502.php
You're done!