13

Nginx反向代理502 Bad Gateway

 3 years ago
source link: https://www.leixuesong.com/606
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Nginx反向代理502 Bad Gateway

Linux Linux运维Nginx服务器 2015年7月28日

Nginx作为反向代理时,访问出现502 Bad Gateway是比较常见的错误。我们从多个方面来分析访问出现Nginx 502  Bad Gateway的原因,并提供一些使用的解决办法。任何时候出现错误,查看日志是一个好的解决办法。

一、出现错误,首先要查找nginx的日志文件,nginx默认日志目录为/var/log/nginx,在日志中发现了如下错误。
2015/07/28 03:33:47 [error] 15421#0: *16 upstream sent too big header while reading response header from upstream
这个错误可能是nginx缓冲区有一个bug造成的,我们网站的页面消耗占用缓冲区可能过大。增加缓冲区的方法,可以彻底解决了Nginx 502 Bad Gateway的问题。设置如下:
a、fastcgi缓冲区设置过小

1
2
3
4
5
6
http {
...
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
...
}

可以根据运行的情况自行调整上述两个配置项。

b、代理缓冲区设置过小,引发upstream sent too big header
如果你使用的是nginx反向代理,如果header过大,超出了默认的1k,就会 (说白了就是nginx把外部请求给后端处理,后端返回的header太大,nginx处理不过来就会导致502。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {

listen 80;
server_name www.leixuesong.com;

location / {
#修改配置
###############
proxy_buffer_size 64k;
proxy_buffers 32 32k;
proxy_busy_buffers_size 128k;
###############
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
............
}

二、默认php-cgi的进程数设置过少,nginx没有没有返回
因为默认php-cgi的max_children进程是5个,max_requests默认值是500,可能因为php-cgi进程不够用而造成502,需要修改/usr/local/php/etc/php-fpm.conf 将其中的max_children值适当增加。也有可能是max_requests值不够用。这两个配置项占用内存很大,请根据服务器配置进行设置。否则可能起到反效果。

三、nginx响应超时
a、php程序执行超时
php执行超时,修改/usr/local/php/etc/php.ini 将max_execution_time 改为300,或者程序中设置执行最大时间set_time_limit函数,该函数必须在文件第一行设置。

b、nginx等待时间超时
部分PHP程序的执行时间超过了Nginx的等待时间,可以适当增加nginx.conf配置文件中FastCGI的timeout时间

1
2
3
4
5
6
http {
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
......
}

来源:Nginx反向代理502 Bad Gateway


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK