我在使用 tiangolo/uwsgi-nginx-flask 部署flask應用的時候,常常運行一下子就出現502錯誤,從新啓動容器後,就恢復。react
且常常會出現數據更新後,刷新結果不一致。nginx
docker做者的github中也有人遇到相似問題。https://github.com/tiangolo/uwsgi-nginx-flask-docker/issues/92git
查詢容器的日誌能夠看到upstream prematurely closed connection while reading response header from upstreamgithub
說是鏈接沒有釋放。現將解決方案記錄一下:sql
http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/docker
在flask文檔中有介紹使用一個裝飾器來進行session釋放。flask
from yourapplication.database import db_session @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
具體適用方法以下:session
一:app
from flask import Flask from yourapplication.database import db_session app = Flask(name) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
二:spa
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()