VPS部署FastAPI Python框架


FastAPI是Python高性能异步Web框架,基于ASGI标准,性能接近Node.js和Go。FastAPI内置自动API文档(Swagger UI)、类型验证和异步支持,非常适合构建REST API。本文介绍在搬瓦工VPS上部署FastAPI的完整流程。

环境准备

# 安装Python 3.9+
sudo apt update
sudo apt install python3 python3-pip python3-venv -y

# 创建项目目录
sudo mkdir -p /var/www/fastapi-app
sudo chown $USER:$USER /var/www/fastapi-app
cd /var/www/fastapi-app

# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate

# 安装FastAPI和相关依赖
pip install fastapi uvicorn[standard] gunicorn

创建FastAPI应用

创建 main.py

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

app = FastAPI(
    title="My API",
    description="FastAPI Application",
    version="1.0.0"
)

class Item(BaseModel):
    name: str
    price: float
    description: str = None

@app.get("/")
async def root():
    return {"message": "Hello from FastAPI!", "status": "running"}

@app.get("/health")
async def health_check():
    return {"status": "ok"}

@app.post("/items/")
async def create_item(item: Item):
    return {"item": item, "message": "Item created"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}
# 测试运行(开发模式)
uvicorn main:app --host 127.0.0.1 --port 8000 --reload

# 访问API文档
# http://127.0.0.1:8000/docs    (Swagger UI)
# http://127.0.0.1:8000/redoc   (ReDoc)

Uvicorn生产部署

Uvicorn是FastAPI推荐的ASGI服务器,支持异步处理:

# 单进程启动(适合测试)
uvicorn main:app --host 127.0.0.1 --port 8000

# 多Worker启动
uvicorn main:app --host 127.0.0.1 --port 8000 --workers 3

Gunicorn + Uvicorn Workers(推荐)

生产环境推荐使用Gunicorn管理Uvicorn Worker,更加稳定:

pip install gunicorn uvicorn[standard]

# 直接启动
gunicorn main:app -w 3 -k uvicorn.workers.UvicornWorker -b 127.0.0.1:8000

创建Gunicorn配置文件 gunicorn.conf.py

# 绑定地址
bind = "127.0.0.1:8000"

# Worker数量(2*CPU+1)
workers = 3

# Worker类型(必须使用UvicornWorker)
worker_class = "uvicorn.workers.UvicornWorker"

# 超时
timeout = 120
graceful_timeout = 30
keepalive = 5

# 最大请求数
max_requests = 1000
max_requests_jitter = 50

# 日志
accesslog = "/var/log/fastapi/access.log"
errorlog = "/var/log/fastapi/error.log"
loglevel = "warning"

# 进程名
proc_name = "fastapi-app"
# 创建日志目录
sudo mkdir -p /var/log/fastapi

# 使用配置文件启动
gunicorn -c gunicorn.conf.py main:app

Systemd服务

sudo nano /etc/systemd/system/fastapi.service
[Unit]
Description=FastAPI Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/fastapi-app
Environment="PATH=/var/www/fastapi-app/venv/bin"
ExecStart=/var/www/fastapi-app/venv/bin/gunicorn -c gunicorn.conf.py main:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
RestartSec=5
KillMode=mixed

[Install]
WantedBy=multi-user.target
sudo chown -R www-data:www-data /var/www/fastapi-app
sudo chown -R www-data:www-data /var/log/fastapi

sudo systemctl daemon-reload
sudo systemctl enable fastapi
sudo systemctl start fastapi
sudo systemctl status fastapi

Nginx反向代理

sudo nano /etc/nginx/conf.d/fastapi.conf
server {
    listen 80;
    server_name api.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;

    # 请求体大小限制
    client_max_body_size 10M;

    location / {
        proxy_pass http://127.0.0.1:8000;
        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;

        # WebSocket支持(FastAPI WebSocket端点)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # 静态文件
    location /static/ {
        alias /var/www/fastapi-app/static/;
        expires 30d;
    }
}
sudo nginx -t
sudo nginx -s reload

项目结构建议

fastapi-app/
├── main.py                 # 应用入口
├── gunicorn.conf.py        # Gunicorn配置
├── requirements.txt        # 依赖列表
├── .env                    # 环境变量
├── app/
│   ├── __init__.py
│   ├── routers/            # 路由模块
│   │   ├── users.py
│   │   └── items.py
│   ├── models/             # 数据模型
│   ├── schemas/            # Pydantic模型
│   ├── services/           # 业务逻辑
│   └── database.py         # 数据库配置
├── static/                 # 静态文件
└── tests/                  # 测试

更新部署

cd /var/www/fastapi-app
source venv/bin/activate

# 拉取代码
git pull origin main

# 更新依赖
pip install -r requirements.txt

# 数据库迁移(如果使用Alembic)
alembic upgrade head

# 重启服务
sudo systemctl restart fastapi

# 查看状态
sudo systemctl status fastapi
curl http://127.0.0.1:8000/health

常见问题

Tip: Flask/Django部署请参考 Python Flask/Django部署教程。更多教程请查看新手教程
关于本站

搬瓦工VPS中文网(bwgvps.com)是非官方中文信息站,整理搬瓦工 BandwagonHost 的优惠信息、使用教程和方案对比,方便中文用户选购和使用。

新手必读
搬瓦工优惠码

当前最大折扣优惠码:

NODESEEK2026(优惠 6.77%)

在购买方案时填入优惠码即可自动抵扣。详见 优惠码使用教程