Nginx 504 Gateway Time-out

Published on May 30, 2018

背景

Nginx + Tomcat搭建的服务器,客户反映在在访问系统过程中会出现504 Gateway Timeout的错误,出现的频率还不低,但看上去并没什么规律。

Nginx代理配置如下

upstream test {
  server  192.168.0.28:9087 weight=1;
}

server {
    listen       81;
    server_name  localhost;
    charset utf-8;
    
    location / { 
        proxy_pass http://test; 
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    } 
}

解决

一定要查看自己的Nginx日志/usr/local/nginx/logs/error.log,504错误有很多原因可以导致。

2018/05/30 11:46:01 [error] 1079#0: *410384 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.0.218, server: localhost, request: "POST /wto-gis/gisView/getBsSiteMapInfo.do HTTP/1.1", upstream: "http://192.168.0.28:9087/wto-gis/gisView/getBsSiteMapInfo.do", host: "192.168.0.28:81"

其中最重要的信息upstream timed out (110: Connection timed out) while reading response header from upstream,表示在读取来自upstream的响应头时超时了。

出现这个问题时,通常是upstream(上游)服务太慢了,解决该问题的最正确的方法是优化后台服务提升响应速度,但对于那些无能为力的系统或者临时解决方案可以修改Nginx配置来屏蔽掉504错误。

Nginx有两个配置指令来设置读取响应的时长,单位为秒:

proxy_read_timeout – Defines a timeout for reading a response from the proxied server. Default is 60 seconds.

fastcgi_read_timeout – Defines a timeout for reading a response from the FastCGI server. Default is 60 seconds.

使用哪一个就要查看你的Nginx的错误日志,upstream是常规的proxy upstream: "http://192.168.0.28:9087"还是fastcgi upstream: “fastcgi: //127.0.0.1:9000”。 知道了upstream类型,就可以相应地来调整proxy_read_timeout或fastcgi_read_timeout。

比如我的日志是upstream: "http://192.168.0.28:9087/wto-gis/gisView/getBsSiteMapInfo.do",所以最终只要在配置中加入如下配置就暂时屏蔽了504错误。

...
location / { 
	...
	proxy_read_timeout 90; #时长根据自身情况来定
}
...