Python 项目生产化部署:Docker + Gunicorn + Nginx 完整指南

将 Python 应用从本地开发环境部署到生产环境,需要考虑性能、安全、可扩展性等多个维度。本文提供一套经过生产验证的部署方案。

一、应用示例:FastAPI 项目

1.1 项目结构

myapp/
├── app/
│   ├── __init__.py
│   ├── main.py           # FastAPI 应用入口
│   ├── routers/
│   ├── models.py
│   └── config.py
├── tests/
├── Dockerfile
├── docker-compose.yml
├── gunicorn.conf.py
├── nginx.conf
├── requirements.txt
└── .dockerignore

1.2 应用代码

# app/main.py
from fastapi import FastAPI, HTTPException
from contextlib import asynccontextmanager
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动事件
    logger.info("Application starting up...")
    await init_db()
    yield
    # 关闭事件
    logger.info("Application shutting down...")
    await close_db()

app = FastAPI(
    title="Production API",
    description="A production-ready FastAPI application",
    version="1.0.0",
    lifespan=lifespan
)

@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": "1.0.0"}

@app.get("/")
async def root():
    return {"message": "Welcome to Production API"}

二、Docker 容器化

2.1 多阶段构建 Dockerfile

# Dockerfile
# 阶段 1:构建依赖
FROM python:3.11-slim as builder

WORKDIR /app

# 安装编译依赖
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# 安装 Python 依赖到独立目录
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

# 阶段 2:生产镜像
FROM python:3.11-slim

# 创建非 root 用户
RUN groupadd -r appgroup && useradd -r -g appgroup appuser

WORKDIR /app

# 从构建阶段复制依赖
COPY --from=builder /root/.local /home/appuser/.local
ENV PATH=/home/appuser/.local/bin:$PATH

# 复制应用代码
COPY --chown=appuser:appgroup app/ ./app/

# 切换到非 root 用户
USER appuser

# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1

EXPOSE 8000

# 使用 Gunicorn 启动
CMD ["gunicorn", "-c", "gunicorn.conf.py", "app.main:app"]

2.2 依赖管理

# requirements.txt
fastapi==0.104.1
uvicorn[standard]==0.24.0
gunicorn==21.2.0
httptools==0.6.1
python-multipart==0.0.6
pydantic==2.5.0
pydantic-settings==2.1.0
sqlalchemy==2.0.23
asyncpg==0.29.0
redis==5.0.1
prometheus-client==0.19.0

2.3 .dockerignore

__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.venv/
pip-log.txt
pip-delete-this-directory.txt
.tox/
.coverage
.coverage.*
.pytest_cache/
htmlcov/
dist/
build/
*.egg

更多推荐