部署 Flask 应用
轻量 Python WSGI 应用,用 Gunicorn 或 Waitress,部署到 VPS、容器或 serverless。
平台进阶
为什么
Flask 最小核心按需添加,生成小快 Python 服务。Gunicorn 提供生产 WSGI 服务和 worker 进程管理保证可靠性。
平台即服务采用率 2024 年增长 24%,团队从虚拟机管理转向 git push 部署。the cloud infrastructure market reached $330B in 2024, growing 22% year-over-year (Synergy Research),PaaS 层捕获了大多数新工作负载。
何时使用
中小 Python API、内部工具和原型用 Flask。需要 async 和自动验证时选 FastAPI。
如何做
1. WSGI — gunicorn app:app -w 4 -b 0.0.0.0:5000
2. Docker — python:3.12-slim,gunicorn CMD
3. Serverless — Zappa 或 serverless-wsgi 用于 AWS Lambda
4. 环境 — FLASK_ENV=production,从 .env 或环境变量加载
5. Nginx — 反向代理做 TLS 和静态文件
6. Gunicorn worker — (2 * CPU) + 1,或用 gevent 异步
7. 健康检查 — 加 /health 端点供负载均衡器
示例
# app.py
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/health")
def health(): return jsonify(ok=True)
@app.route("/api/data")
def data(): return jsonify(items=[1, 2, 3])
if __name__ == "__main__":
app.run()
# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:5000", "--timeout", "30"]
# gunicorn.conf.py — 生产调优
bind = "0.0.0.0:5000"
workers = 5
timeout = 30
graceful_timeout = 10
常见问题
- ⚠生产用 app.run() — 开发服务器,单线程,非生产用
- ⚠长请求 worker 超时 — 默认 30s,增加或用 gevent 流式
- ⚠大文件上传失败 — Nginx client_max_body_size 太小,nginx 配置中增加
最佳实践
- ✓生产绝不用 Flask 开发服务器 — 始终用 Gunicorn 或 Waitress 多 worker
- ✓I/O 密集应用用 gevent 或 eventlet worker 类 — 处理数千并发连接
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求