Flask-项目部署
这篇讲什么
- 生产链路是「浏览器 → nginx → WSGI 服务器 → Flask 应用」,开发服务器不能上生产;这篇把每一段都在本机跑通。
- Windows 用 waitress、Linux / WSL 用 gunicorn(worker 数、日志、socket 都实测),nginx 负责反向代理和静态文件直出,
ProxyFix处理转发头。 - uWSGI 降为备选并给了与 gunicorn 的参数对照,末尾是 12 项生产配置清单和部署完该做的验收动作。
部署链路
-
老笔记这条链是
客户端 <=> WEB服务器(nginx)<=> WSGI(uWSGI)<=> Python(Flask)<=> 数据库(MySQL)。方向没错,但把 uWSGI 写成了唯一选择,而且少了「Flask 本身只是 WSGI 应用」这层关系。本机实测过的链路是这样:1
浏览器 -> nginx(:8089) -> gunicorn(:8001, 4 worker) -> Flask 应用 -> 数据库
-
三个角色分得很开:nginx 管 HTTP/TLS/静态文件;WSGI 服务器(gunicorn、waitress…)管进程与并发;Flask 只是被调用的那个 WSGI 应用对象。
-
官方部署章开头那句警告要记住:Do not use the development server when deploying to production,「production」指的是「不是开发」,哪怕你只在本机给一个人用。
官方列的部署方式
-
Flask 官方部署章列的自托管 WSGI 服务器有六种,另加反向代理与托管平台:
方式 平台 本机实测 备注 Gunicorn POSIX,不支持 Windows(官方原话:It does not support Windows (but does run on WSL)) 是(WSL) Linux 上的默认选择 Waitress Windows 与 POSIX 都行 是(Windows) 本机 Windows 侧的主路径 mod_wsgi Apache 否 要在 Apache 里跑才选它 uWSGI POSIX 否 官方仍列着,但配置最重 gevent POSIX 否 长连接多时用 -k geventASGI 跨平台 否 Flask 的 ASGI 支持还没落地 -
老笔记通篇只讲 uWSGI,所以这一篇把主路径换成实测过的 waitress(Windows)和 gunicorn(Linux),uWSGI 留在最后一节当备选。
Waitress(Windows)
-
本机 waitress 3.0.2 实测可用。装:
1
pip install waitress
-
编程式启动:
deploy.py 1
2
3
4from waitress import create_server
srv = create_server(app, host="127.0.0.1", port=5003, threads=4)
srv.run() # 阻塞;要放线程里就 threading.Thread(target=srv.run) -
命令行启动(
MODULE:OBJECT就是官方要求的写法):1
python -m waitress --listen=127.0.0.1:5004 app:app
实测输出与响应:
1
2INFO:waitress:Serving on http://127.0.0.1:5006
GET / -> 200 'from waitress cli' -
实测 waitress 起的服务器行为:
1
2
3
4
5GET / -> 200 {'ok': True, 'scheme': 'http', 'host': '127.0.0.1:5003', 'remote': '127.0.0.1'}
Server 响应头 -> 'waitress'
Content-Type -> 'application/json'
GET /static/a.css -> 200,'body{margin:0}'
GET /static/nope.css -> 404 -
也就是说 waitress 下 Flask 的
static/仍然由应用自己发(走的是/static/<path:filename>这条内置路由),生产上一般再套一层 nginx 把它接走。 -
老笔记里
app.run(debug=True, threaded=True)这种写法只属于开发;debug=True带着能在浏览器执行代码的调试器,绝不能出现在部署里。
Gunicorn(Linux / WSL)
-
官方对 Gunicorn 的四句评价:纯 Python、配置简单、有多种 worker、不支持 Windows 但在 WSL 里能跑、装它不需要额外依赖或编译。
-
装与起:
1
2pip install gunicorn
gunicorn -w 4 'app:app'模块:变量是唯一必填参数,等价于from app import app;用工厂函数就写gunicorn -w 4 'hello:create_app()'。 -
-w是进程数,官方建议起点是CPU * 2;默认只有 1 个 worker,对默认的 sync worker 来说几乎肯定不够。 -
请求日志默认不打,只有 worker 信息和错误;要访问日志加
--access-logfile=-。 -
实测(WSL Ubuntu 26.04,venv 里 Flask 3.1.3 + gunicorn 26.2.0):
1
gunicorn -w 4 -b 127.0.0.1:8000 app:app --daemon --pid gunicorn.pid --error-logfile gunicorn.log
1
2
3进程列表:1 个 master + 4 个 worker
连发 5 次 GET / -> Server: gunicorn,worker pid 在 78797 / 78794 之间轮转
{"host":"127.0.0.1:8000","remote":"127.0.0.1","scheme":"http","worker":78794,"xff":null} -
官方还提醒:Gunicorn 不该用 root 跑(否则应用代码也是 root),因此它绑不了 80/443,前面要放 nginx;
-b 0.0.0.0只在没有反代时用,有反代时绑 0.0.0.0 等于给人开了绕过代理的后门。实测这里绑的是127.0.0.1:8001。 -
需要长连接并发时用
-k gevent(要求greenlet>=1.0),这跟 Python 的async/await和 ASGI 都不是一回事。
nginx 反向代理
-
官方给的最小
server段就是把请求转给本地 WSGI 服务器,并把四个X-Forwarded-*头带上:1
2
3
4
5
6
7
8
9
10
11
12server {
listen 80;
server_name _;
location / {
proxy_pass http://127.0.0.1:8000/;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Prefix /;
}
}然后必须「Tell Flask it is Behind a Proxy」,也就是下一节的 ProxyFix。
-
实测用的探针配置(第二个 nginx 实例,
-p指到自己的前缀目录,不动系统那个 :80):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15server {
listen 8089;
server_name blog.test;
location /static/ {
alias /srv/flaskdeploy/static/;
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}实测:
1
2
3
4
5
6nginx -t -> syntax is ok / test is successful
GET /static/a.css -> 200, Server: nginx/1.28.3, Content-Type: text/css, ETag: "6aed9104-10"
GET / -> 200, Server: nginx/1.28.3, Content-Type: application/json
{"host":"127.0.0.1:8089","remote":"127.0.0.1","xff":"127.0.0.1","worker":78888}
GET /static/nope.css -> 404
access log: "GET /static/a.css HTTP/1.1" 200 16 / "GET / HTTP/1.1" 200 96 -
Server头从gunicorn变成nginx、静态文件带ETag且不经应用,这两点合起来就说明反代和静态直出都生效了。
ProxyFix
-
请求经过反代之后,应用在
REMOTE_ADDR里只能看到127.0.0.1,真实访客 IP、原始协议和域名都在X-Forwarded-*头里。ProxyFix就是把这些头写回 WSGI environ。app.py 1
2
3from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1) -
数字是「有几层代理设了这个头」,不是布尔值。本机实测同一请求(
X-Forwarded-For: 9.9.9.9, 8.8.8.8、X-Forwarded-Proto: https、X-Forwarded-Host: blog.example:443、X-Forwarded-Prefix: /blog):配置 remote_addrschemehosturl不加 ProxyFix 127.0.0.1http127.0.0.1:5000http://127.0.0.1:5000/hdrx_for=1, x_proto=1, x_host=1, x_prefix=18.8.8.8httpsblog.examplehttps://blog.example/blog/hdrx_for=29.9.9.9httpsblog.example同上 -
取的是列表从右往左第 N 个,所以代理层数填错会拿到别人的 IP 而不是真实访客的。
-
这些头是客户端也能自己伪造的,所以官方那句「It can be a security issue if you get this configuration wrong」要落实成:只在真的位于 N 层可信代理后面时才开对应的
x_参数,填错就会拿到别人的 IP。 -
Werkzeug 3.1.9 的
ProxyFix没有「可信来源」这一档参数,实测传了直接报错:1
2
3ProxyFix(app.wsgi_app, x_for=1, trusted_proxies=fn)
-> TypeError: ProxyFix.__init__() got an unexpected keyword argument 'trusted_proxies'
签名实测:ProxyFix(app, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0) -
要做来源校验有两条实测过的路:一是让 waitress 来认代理,它的参数表里就有
trusted_proxy、trusted_proxy_count、trusted_proxy_headers、clear_untrusted_proxy_headers(waitress/adjustments.py里能查到);二是在 nginx 侧只放行内网来源,应用根本不接直连请求。 -
ProxyFix 只改 environ(
REMOTE_ADDR、wsgi.url_scheme、HTTP_HOST、SCRIPT_NAME),原始头仍然留在request.headers里,要完整链路自己拆X-Forwarded-For。
静态文件
-
所有请求都转给应用是没必要的:静态文件让 nginx 直接返回,省掉一次进程间往返,还能吃到
ETag、Last-Modified、Accept-Ranges。 -
用
alias还是root取决于路径关系:location /static/ { alias /srv/flaskdeploy/static/; }是把/static/x.css映射到/srv/flaskdeploy/static/x.css;写成root的话 nginx 会把 location 拼在后面,得让目录层级正好是.../static/static/x.css才对,很容易踩。 -
实测踩到的权限坑:一开始工程放在
/root/flaskdeploy,静态文件全 403:1
open() "/root/flaskdeploy/static/a.css" failed (13: Permission denied)
原因是
/root是drwx------,而 nginx 的 worker 跑在user www-data;下,读不到。把工程挪到/srv/flaskdeploy并chmod -R a+rX之后立刻 200。生产上应用目录本来就不该放在/root里。 -
应用侧仍然保留
/static/<path:filename>这条路由(实测 waitress 直连时 200 / 404 都对),nginx 的location /static/只是抢在它前面把请求接走。 -
上传目录同理:
send_from_directory能挡住../../穿越(实测 404),但静态化交给 nginx 更快。
uWSGI(备选)
-
老笔记这一节整段讲的是 uWSGI。它仍在官方列表里,但配置项最多、和 Flask 的耦合最生硬,本机没有安装也没有实测,所以只保留结论性的对照,不当主路径。
-
概念对照:
老笔记的 uWSGI 项 现在的等价物 --http 127.0.0.1:5000gunicorn -b 127.0.0.1:8000/waitress --listen=...--socket 127.0.0.1:5000+uwsgi_passproxy_pass http://127.0.0.1:8000--wsgi-file blog.py --callable appgunicorn 'blog:app'--processes / --threadsgunicorn -w N/waitress --threads=N--daemonize /var/log/uwsgi.loggunicorn --daemon --error-logfile ... -
真要用 uWSGI,注意它需要编译环境,而且
uwsgi_pass走的是它自己的二进制协议,nginx 要编http_uwsgi_module;这套维护成本明显高于 gunicorn。
生产配置清单
-
一台新 app 上和生产相关的配置默认值,实测如下,上线前逐条对着改:
配置 默认值 生产上 DEBUGFalse保持 False,别用 app.run(debug=True)TESTINGFalse只在测试里 True SECRET_KEYNone必须设,走环境变量;不设时 session 写入直接 500 SESSION_COOKIE_SECUREFalse上 HTTPS 后设 True SESSION_COOKIE_HTTPONLYTrue保持 True SESSION_COOKIE_SAMESITENone建议 'Lax'PERMANENT_SESSION_LIFETIMEtimedelta(days=31)按需调短 SERVER_NAMENone一般不设,交给反代 + ProxyFix MAX_CONTENT_LENGTHNone按业务设上限,超限 413 PROPAGATE_EXCEPTIONSNone保持 None,交给日志与错误处理 PREFERRED_URL_SCHEME'http'全站 HTTPS 时改 'https' -
SECRET_KEY实测本机环境变量里也没有,所以「从环境变量读」不是空话——写进代码就等于泄露。 -
部署完的验收动作,四条都能用命令行直接查:
1
2
3curl -k -I https://域名/
curl -k -I https://域名/static/a.css
curl -k -I https://域名/static/不存在.css1
2
3/ -> Server: nginx (不是 Werkzeug 才算走通了反代)
/static/a.css -> 200,带 ETag、Accept-Ranges,说明 nginx 直接发的,没进应用
/static/不存在 -> 404(不是 500),说明静态目录映射对了