首页 › Flask Web 开发 › 部署上线
部署上线
开发服务器(app.run())只适合本地调试,正式环境要使用专门的 WSGI 服务器,并在前面放一个反向代理。
使用 Gunicorn
$ pip install gunicorn
$ gunicorn -w 4 -b 127.0.0.1:8000 app:app
-w 4 表示启动 4 个工作进程,app:app 指"app.py 文件中的 app 对象"。
用 systemd 守护进程
[Unit]
Description=My Flask App
After=network.target
[Service]
User=www-data
WorkingDirectory=/srv/myapp
ExecStart=/srv/myapp/.venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 app:app
Restart=on-failure
[Install]
WantedBy=multi-user.target
反向代理
用 Nginx 或 Caddy 监听 80/443 端口,把请求转发给 Gunicorn,同时负责 HTTPS 证书和静态文件。以 Caddy 为例:
example.com {
reverse_proxy 127.0.0.1:8000
}
上线检查清单
- 关闭
debug; SECRET_KEY等敏感配置从环境变量读取;- 日志写入文件并定期轮转;
- 数据库定期备份。
练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 写出用 Gunicorn 以 2 个工作进程、监听 127.0.0.1:8000 启动 run.py 中 app 的命令。
查看参考答案
$ gunicorn -w 2 -b 127.0.0.1:8000 run:app