[nginx 配置]NGINX 502 Bad Gateway错误怎么解决

时间:2018-09-15  来源:nginx  阅读:

将网上找到的一些和502 Bad Gateway错误有关的问题和排查方法列一下,先从FastCGI配置入手:

1.查看FastCGI进程是否已经启动

NGINX 502错误的含义是sock、端口没被监听造成的。我们先检查fastcgi是否在运行

2.检查系统Fastcgi进程运行情况

除了第一种情况,fastcgi进程数不够用、php执行时间长、或者是php-cgi进程死掉也可能造成nginx的502错误
运行以下命令判断是否接近FastCGI进程,如果fastcgi进程数接近配置文件中设置的数值,表明worker进程数设置太少

 代码如下 netstat -anpo | grep “php-cgi” | wc -l

3.FastCGI执行时间过长
根据实际情况调高以下参数值

 代码如下

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

4.头部太大

nginx和apache一样,有前端缓冲限制,可以调整缓冲参数

 代码如下

fastcgi_buffer_size 32k;
fastcgi_buffers 8 32k;

如果你使用的是nginx的负载均衡Proxying,调整

 代码如下

proxy_buffer_size 16k;
proxy_buffers 4 16k;


5.https转发配置错误

正确的配置方法

 代码如下

server_name www.111cn.net;
location /myproj/repos {
set $fixed_destination $http_destination;
if ( $http_destination ~* ^https(.*)$ )
{
set $fixed_destination http$1;
}
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Destination $fixed_destination;
proxy_pass http://subversion_hosts;
}


当然,还要看你后端用的是哪种类型的FastCGI,我用过的有php-fpm,流量约为单台机器40万PV(动态页面), 现在基本上没有碰到502。

如果上面办法还是无法解决我可参考下面一文章

===================================================另一篇文章==============================

因此如果你服务器并发量非常大,那只能先增加机器,然后按以下方式优化会取得更好效果;但如果你并发不大却出现502,一般都可以归结为配置问题,脚本超时问题。

1.php-fpm进程数不够用

使用 netstat -napo |grep "php-fpm" | wc -l 查看一下当前fastcgi进程个数,如果个数接近conf里配置的上限,就需要调高进程数。

但也不能无休止调高,可以根据服务器内存情况,可以把php-fpm子进程数调到100或以上,在4G内存的服务器上200就可以。


2. 调高调高linux内核打开文件数量

可以使用这些命令(必须是root帐号)

 代码如下

echo "ulimit -HSn 65536" >> /etc/profile

echo "ulimit -HSn 65536" >> /etc/rc.local

source /etc/profile

 3.脚本执行时间超时

如果脚本因为某种原因长时间等待不返回 ,导致新来的请求不能得到处理,可以适当调小如下配置。

nginx.conf里面主要是如下

 代码如下

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

php-fpm.conf里如要是如下

 代码如下

request_terminate_timeout = 10s

4.缓存设置比较小

修改或增加配置到nginx.conf

 代码如下

proxy_buffer_size 64k;
proxy_buffers  512k;
proxy_busy_buffers_size 128k;

5. recv() failed (104: Connection reset by peer) while reading response header from upstream

可能的原因机房网络丢包或者机房有硬件防火墙禁止访问该域名

但最重要的是程序里要设置好超时,不要使用php-fpm的request_terminate_timeout,

最好设成

 代码如下 request_terminate_timeout=0;

因为这个参数会直接杀掉php进程,然后重启php进程,这样前端nginx就会返回104: Connection reset by peer。这个过程是很慢,总体感觉就是网站很卡。

May 01 10:50:58.044162 [WARNING] [pool www] child 4074, script "/usr/local/nginx/html/quancha/sameip/detail.php" execution timed out (15.129933 sec), terminating May 01 10:50:58.045725 [WARNING] [pool www] child 4074 exited on signal 15 SIGTERM after 90.227060 seconds from start May 01 10:50:58.046818 [NOTICE] [pool www] child 4082 started

说一千道一万最重要的就是程序里控制好超时,gethostbyname、curl、file_get_contents等函数的都要设置超时时间。

[nginx 配置]NGINX 502 Bad Gateway错误怎么解决

http://m.bbyears.com/caozuoxitong/44372.html

推荐访问:nginx负载均衡配置
相关阅读 猜你喜欢
本类排行 本类最新