FastAPI 全栈后端(八):部署与运维

创作者: Yardon | GitHub: github.com/YardonYan | 版本: v1.0 |



开发 vs 生产环境配置

python 复制代码
# config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    APP_NAME: str = "MyApp"
    DATABASE_URL: str
    SECRET_KEY: str
    DEBUG: bool = False

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"

settings = Settings()
bash 复制代码
# .env
DATABASE_URL=postgresql+asyncpg://user:pass@localhost/mydb
SECRET_KEY=change-me-in-production
DEBUG=true

Uvicorn 运行配置

bash 复制代码
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 --reload
参数 说明
--workers 进程数(生产用)
--reload 热重载(仅开发)
--log-level 日志级别

Gunicorn + Uvicorn Workers

Gunicorn 负责进程管理,Uvicorn 处理异步:

bash 复制代码
gunicorn main:app \
  -w 4 \
  -k uvicorn.workers.UvicornWorker \
  -b 0.0.0.0:8000 \
  --log-level info

Docker 容器化

dockerfile 复制代码
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
yaml 复制代码
# docker-compose.yml
services:
  api:
    build: .
    ports: ["8000:8000"]
    env_file: .env
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:16-alpine
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

健康检查与监控

python 复制代码
from fastapi import FastAPI

app = FastAPI()

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

@app.get("/ready")
async def ready():
    # 检查数据库连接
    try:
        await db.execute(select(1))
        return {"status": "ready"}
    except Exception as e:
        raise HTTPException(status_code=503, detail=str(e))

Nginx 配合健康检查做负载均衡:

nginx 复制代码
upstream api_backend {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
}

server {
    location / {
        proxy_pass http://api_backend;
        proxy_set_header Host $host;
    }
    location /health {
        proxy_pass http://api_backend/health;
    }
}

环境变量与安全

bash 复制代码
# 永远不要把 secrets 提交到 Git!
# .gitignore
.env
.env.*
python 复制代码
import os
SECRET_KEY = os.getenv("SECRET_KEY")  # Kubernetes Secret 注入

日志管理

python 复制代码
import logging
from contextlib import asynccontextmanager
import structlog

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.JSONRenderer()
    ]
)

FastAPI 全栈总结

章节 核心内容
第1章 FastAPI vs Flask,类型驱动,自动文档
第2章 RESTful 路由,Pydantic 模型,请求/响应模型
第3章 SQLAlchemy 2.0 异步,Alembic 迁移
第4章 JWT 认证,bcrypt 密码,OAuth2
第5章 BackgroundTasks / Celery 后台任务
第6章 中间件,CORS,依赖注入
第7章 pytest + TestClient 异步测试
第8章 Docker 部署,Gunicorn,Nginx,健康检查

📌 创作者: Yardon | 🏠 个人网站: GlimmerAI.top

📖 本章是「FastAPI 全栈后端」系列的终章!FastAPI 路线全部完成 🎉

🎉 下一个系列:「LangChain + RAG 实战」------构建你的第一个 AI 应用。欢迎大家来观看!

相关推荐
运维行者_3 小时前
企业无线网络监控的挑战与智能化演进趋势
大数据·运维·服务器·网络·数据库
2603_955279703 小时前
Cursor + GitOps:自动化运维新姿势
运维·自动化
国强_dev3 小时前
技术探讨:使用 stunnel 加密转发数据库连接时,如何获取客户端真实 IP?
数据库·网络协议·tcp/ip
@insist1233 小时前
系统规划与管理师-信息系统规划核心工作要点解析
数据库·软考·系统规划与管理师·软件水平考试·系统规划与管理工程师
超级数据查看器3 小时前
超级数据查看器 v10.0 发布
java·大数据·数据库·sqlite·安卓
Waay3 小时前
面试口述版:个人对 Prometheus 完整理解
运维·学习·云原生·面试·职场和发展·kubernetes·prometheus
数安3000天4 小时前
增量数据如何自动分类分级,避免目录“过期“?
大数据·数据库
三8444 小时前
文件查找/文件压缩/解压缩
linux·运维·服务器
小猪写代码4 小时前
Linux 管道(Pipeline)作业
linux·运维·服务器
AI行业学习4 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++