从开发到生产:使用Docker Compose和Nginx部署Python FastAPI应用

以下是完整的部署流程,所有步骤均经过生产环境验证。部署架构如下图所示:

用户请求 → Nginx(反向代理/静态文件) → FastAPI容器(动态请求)


步骤1:准备FastAPI应用
  1. 基础项目结构:

    myapp/
    ├── app/
    │   ├── main.py          # FastAPI主程序
    │   ├── requirements.txt # 依赖文件
    │   └── static/          # 静态文件目录
    ├── Dockerfile           # 应用镜像构建
    └── docker-compose.yml   # 服务编排
    

  2. 示例main.py

    from fastapi import FastAPI
    app = FastAPI()
    
    @app.get("/")
    async def root():
        return {"message": "Hello from Docker!"}
    

  3. requirements.txt内容:

    fastapi
    uvicorn[standard]
    


步骤2:构建应用Docker镜像

创建Dockerfile

# 基础镜像
FROM python:3.9-slim

# 设置工作目录
WORKDIR /app

# 安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

# 启动命令
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

验证镜像构建:

docker build -t fastapi-app .


步骤3:配置Nginx反向代理
  1. 创建nginx/conf.d/app.conf

    server {
        listen 80;
        
        # 静态文件处理
        location /static/ {
            alias /var/www/static/;
        }
        
        # 动态请求转发
        location / {
            proxy_pass http://web:8000;  # 指向compose中的服务名
            proxy_set_header Host $host;
        }
    }
    

  2. 创建nginx/Dockerfile

FROM nginx:alpine
COPY conf.d/app.conf /etc/nginx/conf.d/default.conf


步骤4:编排服务

docker-compose.yml配置:

version: '3.8'

services:
  web:
    build: .
    volumes:
      - ./app/static:/app/static  # 挂载静态文件
    ports:
      - "8000:8000"
    restart: always

  nginx:
    build: ./nginx
    ports:
      - "80:80"
    volumes:
      - ./app/static:/var/www/static  # 与web容器共享静态文件
    depends_on:
      - web


步骤5:启动生产环境
docker-compose up -d --build

验证部署:

  1. 检查服务状态:
    docker-compose ps
    

  2. 测试访问:
    curl http://localhost
    # 输出: {"message":"Hello from Docker!"}
    


性能优化建议
  1. 静态文件加速
    在Nginx配置中添加缓存头:

    location /static/ {
        expires 30d;
        add_header Cache-Control "public";
    }
    

  2. Gzip压缩
    nginx.conf中启用:

    gzip on;
    gzip_types text/plain application/json;
    

  3. 负载均衡
    扩展web容器实例:

    docker-compose up -d --scale web=3
    

    在Nginx配置中添加upstream

    upstream fastapi_servers {
        server web:8000;
        server web:8000;
        server web:8000;
    }
    

    proxy_pass改为:

    proxy_pass http://fastapi_servers;
    


监控与维护
  1. 日志查看:
    docker-compose logs -f
    

  2. 更新流程:
    docker-compose down
    git pull origin main
    docker-compose up -d --build
    

通过此方案,可实现:

  • ✅ 开发与生产环境一致性
  • ✅ 动态请求与静态资源分离
  • ✅ 水平扩展能力
  • ✅ 零停机更新(配合docker-compose restart

更多推荐