Python Flask/FastAPI应用部署到VPS:Gunicorn+Nginx反向代理完整方案
为什么不能直接用 Flask 开发服务器上线?
Flask 和 FastAPI 内置的开发服务器(flask run 或 uvicorn main:app)只适合本地调试,单线程、不支持并发、缺乏错误恢复机制,生产环境必须使用 Gunicorn(WSGI)或 Uvicorn(ASGI)配合 Nginx 反向代理。
一、环境准备
sudo apt update
sudo apt install python3 python3-pip python3-venv nginx -y
# 创建项目目录
mkdir ~/myapp && cd ~/myapp
# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate
# Flask 项目安装依赖
pip install flask gunicorn
# FastAPI 项目安装依赖
# pip install fastapi uvicorn[standard] gunicorn二、Flask 应用示例
nano app.pyfrom flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return jsonify({"status": "ok", "message": "Hello from Flask!"})
@app.route('/health')
def health():
return jsonify({"status": "healthy"})
if __name__ == '__main__':
app.run()三、Gunicorn 启动配置
创建 Gunicorn 配置文件:
nano gunicorn.conf.py# 绑定地址(只监听本地,由 Nginx 反向代理)
bind = "127.0.0.1:8000"
# worker 数量:推荐 CPU 核心数 × 2 + 1
workers = 3
# 每个 worker 的线程数(Flask 用 sync worker)
threads = 2
# 请求超时时间(秒)
timeout = 60
# 日志配置
accesslog = "/var/log/gunicorn/access.log"
errorlog = "/var/log/gunicorn/error.log"
loglevel = "info"
# 进程名称
proc_name = "myapp"# 创建日志目录
sudo mkdir -p /var/log/gunicorn
sudo chown youruser:youruser /var/log/gunicorn
# 测试启动
gunicorn -c gunicorn.conf.py app:app看到 Booting worker with pid 的输出说明启动成功。
四、FastAPI + Uvicorn 配置(异步框架)
nano main.pyfrom fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello from FastAPI!"}
@app.get("/health")
async def health():
return {"status": "healthy"}FastAPI 使用 Uvicorn worker:
# gunicorn.conf.py for FastAPI
bind = "127.0.0.1:8000"
workers = 3
worker_class = "uvicorn.workers.UvicornWorker"
timeout = 60gunicorn -c gunicorn.conf.py main:app五、systemd 进程守护
sudo nano /etc/systemd/system/myapp.service[Unit]
Description=My Python Web App
After=network.target
[Service]
Type=simple
User=youruser
WorkingDirectory=/home/youruser/myapp
ExecStart=/home/youruser/myapp/venv/bin/gunicorn -c gunicorn.conf.py app:app
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp六、Nginx 反向代理配置
sudo nano /etc/nginx/sites-available/myappserver {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s;
}
# 静态文件直接由 Nginx 提供,不经过 Python
location /static/ {
alias /home/youruser/myapp/static/;
expires 30d;
}
}sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx用 Certbot 申请 HTTPS 证书:
sudo certbot --nginx -d your-domain.com总结
Python Web 应用生产部署的标准架构:Gunicorn/Uvicorn(多进程应用服务器)+ systemd(进程守护)+ Nginx(反向代理 + 静态文件 + SSL)。这套架构稳定成熟,适合从小型 API 到中型 Web 应用的各种规模。
IDC.Net 香港云服务器首月 10 元起,Ubuntu 22.04 开箱即用,CN2 GIA 直连大陆,支持支付宝付款,适合 Python 应用的生产部署。
版权声明:
作者:后浪云
链接:https://idc.net/help/442562/
文章版权归作者所有,未经允许请勿转载。
THE END
