公司网站经常会遇到访问出现502,我理解的原因有php-fpm资源不够,通常大的并发下会经常出现这个问题,或者某些进程执行时间较长。
我的解决方案是 使用 crond 定时查看进程运行的状态,发现不对立马重启。
1.我用的是php脚本监测的。
<?php
$url = '要监测的网站域名';
$cmd = 'service php-fpm restart';
for($i = 0; $i < 1; $i ++){
$exec = "curl connect-timeout 3 -I $url 2>/dev/null";
$res = shell_exec($exec);
echo "rn".$res.'啥也没有';
if(stripos($res, '502 Bad Gateway') !== false){
echo "rn出现502 并重启php-fpm".date('Y-m-d H:i:s');
$ss= shell_exec($cmd);
echo "rn".$ss;
exit();
}elseif($res==''){
echo "rn程序返回是空 并重启nginx".date('Y-m-d H:i:s');
$cmd = 'service nginx restart';
$ss= shell_exec($cmd);
echo "rn".$ss;
exit();
}else{
echo "rn程序正常";
}
}
2.添加定时任务 crond
2.1)vi /etc/crontab
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
每隔30分钟执行一次root下的nginx-status.php脚本 并将结果存在log文件中:
*/30 * * * * /usr/bin/php /root/nginx-status.php >> /var/log/nginx-log.log
#加载任务,使之生效
crontab /etc/crontab
#查看任务
crontab -l
![945793406b2936a12596805135ca474e.png](https://img-blog.csdnimg.cn/img_convert/945793406b2936a12596805135ca474e.png)
有问题可以私下沟通!