问题 :访问一个接口时,出现 502 Bad Gateway
分析:
1.报错显示和nginx有关,所以查看nginx的错误日志error.log
2.发现报upstream prematurely closed connection while reading response header from upstream 在从上游读取响应头时,上游过早关闭连接 这里猜测上游应该指的是服务器,因为后端架构是 nginx+gunicron
3..查看后端日志,发现报[CRITICAL] WORKER TIMEOUT ,则是指后端服务器超时,我这里是gunicorn
步骤:
1.改变gunicorn 的超时时间,默认是30s,由于我这个接口对时间没要去,所以把gunicorn的超时间设置为5分钟,即 -t 300
gunicorn app.main:app -t 300 -w 8
2.再次请求接口时,发现报 504 Gateway Time-out,但nginx的error.log 不再报upstream prematurely closed connection while reading response header from upstream,nginx访问出现504 Gateway Time-out,一般是由于程序执行时间过长导致响应超时,例如程序需要执行90秒,而nginx最大响应等待时间为30秒,这样就会出现超时。把proxy_read_timeout 设置为300;请求正常。
总结:
出现的问题是:在从上游读取响应头时,上游过早关闭连接,本质是服务器那边设置的请求超时时间默认为30s,而nginx 默认时间是60s。改变这两个默认时间,问题就解决了。