首页 > 当nginx显示502 Bad Gateway错误,如何实现用户无感知的自动重启php-fpm

当nginx显示502 Bad Gateway错误,如何实现用户无感知的自动重启php-fpm

最近nginx间隙性的出现502错误,如何实现自动重启php-fpm呢

想到的解决方案

1、使用crontab定时执行shell脚本,出现错误后重启(每5秒定时执行)
2、使用nohup,shell脚本后台执行

示例脚本

#!/bin/bash
        
while : 
do   

    URL="http://192.168.1.30"
    RESULT=`curl -m 10 -I -s  $URL | grep "HTTP/1.1 502"`
    if [ -n "$RESULT" ]; then
        /etc/init.d/php-fpm restart
    fi  
    sleep 5
done 

3、编写nginx模块,通过条件执行shell脚本

能想到的也就是这几种了,感觉这几种方案都不太好,谁有更好的解决方案?


Nginx可以配置fastcgi_next_upstream实现故障转移,比如:

fastcgi_next_upstream error timeout invalid_header http_500 http_503;

后端PHP-FPM返回error、timeout等信息则自动切换到upstream里的下一台PHP-FPM应用服务器。

个人觉得最好还是找出PHP-FPM工作进程崩溃的原因,是代码问题,还是系统资源不足导致响应超时。
注意两点,一是不要在PHP-FPM里执行耗时太长或不确定的代码,比如curl发出网络请求。二是PHP-FPM工作进程不是越多越好,个人认为,PHP-FPM工作进程数,设置为2倍CPU核心数就足够了。毕竟,Nginx和MySQL以及系统同样要消耗CPU。根据服务器内存来设置PHP-FPM进程数是非常不合理的,把内存分配给MySQL、Memcached这些服务显然更合适,过多的PHP-FPM进程反而会增加CPU上下文切换的开销。


受到fastcgi_next_upstream这个参数的启发,使用PHP-FPM线程池的概念,可以完美的解决502错误(http_502是没有的

http里面的配置

upstream php_fpm_sock{
    server unix:/dev/shm/php-fpm.socket;
    server unix:/dev/shm/php-fpm-b.socket;
    server unix:/dev/shm/php-fpm-c.socket;
}   
fastcgi_next_upstream error timeout invalid_header http_503  http_500;

server里面fastcgi_pass配置

location ~* \.php$ {
    fastcgi_pass    **unix:php_fpm_sock;**
    fastcgi_index   index.php;
    client_max_body_size 50M;
    client_body_temp_path /data/www/tmp;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi.conf;
    include        fastcgi_params;
}      

php-fpm的配置

#/etc/php-fpm.conf 文件包含多个配置文件
include=/etc/php-fpm.d/*.conf

#/etc/php-fpm.d/ 目录
www-a.conf
www-b.conf
www-c.conf
#配置,三个文件这里不一致,分别对应
#Start a new pool named www-a   
                                                                          
[www-a]
listen = /dev/shm/php-fpm.socket

ps -ef 查看

www      17996 31539  0 12:13 ?        00:00:51 php-fpm: pool www-b
www      17999 31539  0 12:13 ?        00:00:48 php-fpm: pool www-a
www      18010 31539  0 12:14 ?        00:00:46 php-fpm: pool www-b
www      18063 31539  0 12:25 ?        00:00:42 php-fpm: pool www-c
www      18153 31539  0 12:47 ?        00:00:34 php-fpm: pool www-c
www      18154 31539  1 12:47 ?        00:00:37 php-fpm: pool www-a
www      18185 31539  0 12:55 ?        00:00:29 php-fpm: pool www-c
www      18313 31539  0 13:24 ?        00:00:10 php-fpm: pool www-a

1、启动的各个PHP-FPM线程池,只要不都挂掉,nginx就可以正常执行PHP,如果有的异常退出了,基本也不影响网站运行
2、fastcgi_next_upstream那行的参数,不需要加http_502,实际你也加不上去的
3、原有的每段类似这种location ~ \.php$ {} 代码都需要对fastcgi_pass这行根据示例改造

【热门文章】
【热门文章】