修改 Elastic Beanstalk 环境的配置文件/etc/nginx/nginx.conf
,将 proxy_read_timeout
和 proxy_connect_timeout
的值增加到较大的数值。如:
http {
...
proxy_read_timeout 600s;
proxy_connect_timeout 600s;
...
}
在 Flask 应用中增加以下代码:
from flask import Flask
app = Flask(__name__)
@app.after_request
def after_request(response):
if not app.debug:
response.headers['X-Forwarded-Proto'] = 'https'
return response
这段代码会在请求结束后添加一个名为X-Forwarded-Proto
的 header,告诉 Elastic Beanstalk 使用 HTTPS 协议。这可以解决一些超时错误。
在 Elastic Beanstalk 环境的配置页面中,配置Load Balancer
的 idle timeout(闲置超时)选项,将其设置为足够大的数值。如:
# 截图是已经设置超时为 1800 秒
以上方法可以一定程度上避免 504 Gateway Timeout 错误。