情况:
- nginx服务器正常,gunicorn正常运行,flask也可以运行。
- 从flask直接连外网——正常访问
- nginx连接flask——正常访问
- flask上包裹一层gunicorn,再用nginx连接gunicorn——错误代码502
博主抠了半天脑壳,可是网页总是如下(博主在nginx设置的50x.html):
最后终于找到了问题。
原来博主在nginx设置的转发地址如下是https协议的。
proxy_pass https://127.0.0.1:5001;
博主在flask也编写了https接口,所以nginx转发到flask也可以正常访问。但是直接使用如下代码同gunicorn启动flask,会报错。原因在于gunicorn包住了flask,其接口是http协议的。所以请求从起前端发送上来经过nginx到gunicorn,gunicorn不认识https的请求就卡住了。
gunicorn -w 2 -b 127.0.0.1:5001 server:app
解决方案:
- nginx(转发地址)、gunicorn、flask全部配置成https
- 或者统一使用http。flask别带SSL证书。nginx转发接口改成如下形式:
proxy_pass http://127.0.0.1:5001;
当然你可以在nginx同时配置http和https来兼容两种访问方式,对外界访问不影响