解决flask的502错误:upstream prematurely closed connection while reading response header from upstream

时间:2022-05-22 17:35:47

我在使用 tiangolo/uwsgi-nginx-flask 部署flask应用的时候,经常运行一会儿就出现502错误,重新启动容器后,就恢复。

且经常会出现数据更新后,刷新结果不一致。

docker作者的github中也有人遇到类似问题。https://github.com/tiangolo/uwsgi-nginx-flask-docker/issues/92

查询容器的日志可以看到upstream prematurely closed connection while reading response header from upstream

说是连接没有释放。现将解决方案记录一下:

http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/

在flask文档中有介绍使用一个装饰器来进行session释放。

from yourapplication.database import db_session

@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()

具体适用方法如下:

一:

from flask import Flask
from yourapplication.database import db_session
app = Flask(name)
@app.teardown_appcontext
def shutdown_session(exception=None):
  db_session.remove()

二:

from flask import Flask
from yourapplication.database import db_session
def create_app():
app = Flask(name)
return app
app = create_app() @app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()