跳转至

部署到生产环境

在本页中,你将在 production 级别创建 shop,在容器中运行它,并在发布之前对它进行检查。你将了解 FastAPI 如何按环境读取设置,使用 JWT 令牌的 OAuth2 密码流程如何保护端点,中间件的作用(这里用于请求 ID 和结构化日志),以及 FastAPI 如何借助 /health 和 /ready 探针在容器中运行。你还会认识 fastkit 的 production 功能组合、它的 Docker Compose 文件中的 migrate 服务,以及 fastkit doctor。

创建项目

production 级别就是 domain 级别加上一组功能。和上一页一样,请在还没有 shop 的文件夹中操作:

$ fastkit init --level production --name shop --no-venv -y
...
│ Features        │ Authentication: JWT; Testing: Coverage; Migrations:        │
│                 │ Alembic; Developer tooling: ruff, github-actions; Logging: │
│                 │ structured; Deployment: Docker, docker-compose             │
...
$ cd shop
$ ls -A
.dockerignore       Dockerfile      pyproject.toml
.env            README.md       requirements-dev.txt
.env.example        alembic         requirements.txt
.gitattributes      alembic.ini     scripts
.github         conftest.py     src
.gitignore      docker-compose.yml  tests

除了 items 领域,src/app/domains/ 中还有一个 auth 领域;src/app/logging_config.py 负责配置日志。README.md 在“Selected features”下介绍了每项功能。

设置和密钥

src/app/core/config.py 从环境变量和 .env 中读取设置;同名时,环境变量优先于 .env。fastkit 生成 .env 时写入了一个唯一的密钥(SECRET_KEY=...),并且 Git 会忽略 .env。这个密钥用于为下文的访问令牌签名,因此必须保密。设置 ENVIRONMENT 的取值为 development、staging 或 production;在开发环境之外,如果密钥强度不够,应用会拒绝启动:

$ uv sync -q
$ env ENVIRONMENT=production SECRET_KEY=too-short uv run uvicorn src.app.main:app
...
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
  Value error, SECRET_KEY must be at least 32 bytes when ENVIRONMENT=production. Generate one with `python -c "import secrets; print(secrets.token_urlsafe(32))"` and set it as SECRET_KEY in the environment or .env. [type=value_error, input_value={'ENVIRONMENT': 'producti...ECRET_KEY': 'too-short'}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.14/v/value_error

在容器中运行

容器镜像包含你的应用以及 Python 和所需的包,因此只要有 Docker,它在哪里运行都一样。Dockerfile 描述了这个镜像:

Dockerfile
# The image starts from the official slim Python image and adds the app on top.
# https://fastapi.tiangolo.com/deployment/docker/
FROM python:3.12-slim
# ...
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# ...
CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8000"]

docker-compose.yml 会启动三个服务:postgres(数据库)、migrate(运行一次 alembic upgrade head 后退出)和 app,app 要等到数据库状态健康且迁移成功之后才会启动。之后 alembic/versions/ 中的每个修订版本都会作用于这个数据库,所以在自动生成的修订版本到达这一步之前,请先阅读并测试它:例如,Alembic 会把重命名的列看成删除一列再新增一列。

$ docker compose up --build -d
...
 ✔ Container shop-postgres-1    Healthy6.7s
 ✔ Container shop-migrate-1     Exited7.6s
 ✔ Container shop-app-1         Started7.7s
$ curl -s http://127.0.0.1:8000/health
{"status":"ok"}
$ curl -s http://127.0.0.1:8000/ready
{"status":"ok"}

只要进程在运行,/health 就会响应;镜像中的 HEALTHCHECK 会调用它。/ready 还会检查数据库,数据库无法连接时返回 503,这样运行容器的平台就可以只把流量发给已就绪的容器。容器同样会读取 .env。其中设置了 ENVIRONMENT=development,它优先于镜像中的 ENVIRONMENT=production,所以 docker compose up 以开发模式运行应用;README 和 docker-compose.yml 中的注释都说明了这一点。要以生产模式运行,请在 app 服务的 environment: 下添加 ENVIRONMENT=production(这里的条目优先于 .env),然后重新创建应用容器:

docker-compose.yml
    environment:
      - DATABASE_URL=postgresql+asyncpg://${POSTGRES_USER:-user}:${POSTGRES_PASSWORD:-password}@postgres:5432/${POSTGRES_DB:-dbname}
      - ENVIRONMENT=production
$ docker compose up -d
...
$ docker compose exec app printenv ENVIRONMENT
production

Warning

数据库的用户名、密码和数据库名默认为 user、password 和 dbname。docker-compose.yml 以 ${POSTGRES_USER:-user}、${POSTGRES_PASSWORD:-password} 和 ${POSTGRES_DB:-dbname} 的形式从 shell 或 .env 中读取它们,postgres 服务以及 app 和 migrate 的 DATABASE_URL 都使用这些值。请在第一次运行 docker compose up 之前设置好它们:PostgreSQL 只在其数据卷为空时创建账号。如果之后再修改,改变的只是应用发送的值,应用将无法再连接数据库;这时请在 PostgreSQL 内部修改账号,或者用 docker compose down -v 删除数据卷,但这会删除其中的数据。

ENVIRONMENT=production 不会加密通信,而下面的请求会发送密码和令牌。在对外公开应用之前,请在它前面放置一个负责终止 HTTPS 的代理或平台;参见关于 HTTPS。

保护端点

在 OAuth2 密码流程中,客户端把邮箱地址和密码发送到令牌端点,并获得一个访问令牌。这种流程适用于应用自己的客户端,例如应用自己的网页或移动应用;第三方的客户端则使用其他流程,例如授权码流程。JWT 访问令牌是一个经过签名的字符串,其中写明了用户和过期时间。客户端在 Authorization: Bearer <token> 头部中把它发回来,服务器用 SECRET_KEY 验证签名。在 src/app/domains/auth/dependencies.py 中,一个依赖项把这个头部转换成已登录的用户:

src/app/domains/auth/dependencies.py
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/token")

TokenDep = Annotated[str, Depends(oauth2_scheme)]
# ...
async def get_current_user(token: TokenDep, users: UserRepositoryDep) -> User:
    """Resolve the bearer token into a live, active account."""
# ...
CurrentUser = Annotated[User, Depends(get_current_user)]

OAuth2PasswordBearer 从头部读取令牌,缺少令牌时返回 401;它还为 /docs 上的 Swagger UI 提供 Authorize 按钮。get_current_user 检查令牌并加载账号,失败时返回 401。声明了 current_user: CurrentUser 的端点只会为已登录的用户运行,GET /api/v1/users/me 就是这样。下面依次注册、获取令牌(令牌端点读取的是表单而不是 JSON,邮箱放在 username 中),再分别不带令牌和带上令牌调用该端点(请先把 access_token 的值存入 shell 变量:TOKEN=...)。最后一个请求还发送了自己的请求 ID:

$ curl -s -X POST http://127.0.0.1:8000/api/v1/auth/register -H "Content-Type: application/json" -d '{"email": "ada@example.com", "password": "correct-horse-battery"}'
{"id":1,"email":"ada@example.com","full_name":null,"is_active":true}
$ curl -s -X POST http://127.0.0.1:8000/api/v1/auth/token -d "username=ada@example.com" -d "password=correct-horse-battery"
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwidHlwZSI6ImFjY2VzcyIsImlhdCI6MTc5NjMxNzM5NiwiZXhwIjoxNzk2MzE5MTk2fQ.Jkd-gVyg3b9HxgmWbR3-BdraUWRhw826EzDFjlEfifg","token_type":"bearer","expires_in":1800}
$ curl -s -i http://127.0.0.1:8000/api/v1/users/me
HTTP/1.1 401 Unauthorized
...
x-request-id: b6354ce0dfad4b76acb25d2f128f2cb2

{"detail":"Not authenticated"}
$ curl -s -i http://127.0.0.1:8000/api/v1/users/me -H "Authorization: Bearer $TOKEN" -H "X-Request-ID: ada-1"
HTTP/1.1 200 OK
...
x-request-id: ada-1

{"id":1,"email":"ada@example.com","full_name":null,"is_active":true}

production 级别 shop 的 Swagger UI:打开了 OAuth2PasswordBearer 的“Authorize”对话框,已填写用户名和密码,后面是 GET /api/v1/users/me

日志和中间件

中间件是围绕每个请求运行的代码:在端点之前运行,也在响应之后运行。src/app/logging_config.py 添加了一个中间件,它为每个请求分配一个 ID(使用客户端自己的 X-Request-ID,没有时生成一个新的随机 ID),并像上面的响应那样在 X-Request-ID 头部中返回它:

src/app/logging_config.py
# A middleware runs around every request: this one tags it and its logs with an id.
# https://fastapi.tiangolo.com/tutorial/middleware/
class RequestIDMiddleware(BaseHTTPMiddleware):
    """Attach an id to every request and expose it on the response."""

    async def dispatch(
        self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
    ) -> Response:
        request_id = request.headers.get(REQUEST_ID_HEADER) or uuid.uuid4().hex
        # ...
        response.headers[REQUEST_ID_HEADER] = request_id
        return response

在这两步之间,await call_next(request) 让端点作出响应,随后中间件为这个请求写一行访问日志。同一个文件会把每一行日志都写成一个 JSON 对象,日志工具可以按字段搜索它们:

$ docker compose logs app
...
shop-app-1  | {"timestamp": "2026-12-03T17:03:16+0000", "level": "INFO", "logger": "app.access", "message": "GET /api/v1/users/me 401", "request_id": "b6354ce0dfad4b76acb25d2f128f2cb2", "method": "GET", "path": "/api/v1/users/me", "status_code": 401, "duration_ms": 0.51, "client": "192.168.176.1"}
shop-app-1  | {"timestamp": "2026-12-03T17:03:16+0000", "level": "INFO", "logger": "app.access", "message": "GET /api/v1/users/me 200", "request_id": "ada-1", "method": "GET", "path": "/api/v1/users/me", "status_code": 200, "duration_ms": 3.51, "client": "192.168.176.1"}

中间件在 call_next 之前设置 ID,在写完访问日志行之后清除它。在这期间,你的端点和依赖项记录的日志行都带有这个 ID,访问日志行也带有它,所以你可以根据客户端报告的 X-Request-ID 找到该请求的相关日志行。对于未处理的异常,uvicorn 的回溯信息是在此之后写入的,显示为 "request_id": "-";而这个请求的访问日志行(状态码 500)带有该 ID。

持续集成

.github/workflows/test.yml 会在每次推送到 main 以及 GitHub 上的每个拉取请求时运行。它在安装 requirements-dev.txt 之后运行下面的命令。推送之前,uv run bash scripts/lint.sh 会运行 black、isort、mypy 和 ruff check,uv run pytest 会运行测试;生成的项目能通过所有这些检查,也能通过 ruff format --check .(共 101 个测试):

.github/workflows/test.yml
      - name: Lint
        run: |
          ruff check .
          ruff format --check .

      - name: Run tests
        run: pytest

发布之前

fastkit doctor 会检查生成的项目是否存在已知问题,例如提交到 Git 的 .env 或示例用的 SECRET_KEY。有些检查需要 Git 仓库:

$ git init -q
$ git add .
$ fastkit doctor
...
┃Check                 ┃ Status  ┃ Severity ┃ Details                          ┃
┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│env-tracked           │ ok      │ -        │ No .env file is committed to git │
...
╭────────────── Success ───────────────╮
│ ✨ No problems found.                │
╰──────────────────────────────────────╯

只要还有问题没有解决,它就会以状态码 1 退出,因此 CI 任务也可以运行它。检查并修复项目介绍了它如何修复发现的问题。用完之后,docker compose down -v --rmi local 会停止并删除容器,同时删除数据库卷和应用镜像。

FastAPI 文档

下一步

“学习”部分到这里就结束了。操作指南逐一介绍单项任务,可以从选择级别或示例开始阅读;CLI 参考列出了所有命令和选项。