在 Python 的 Web 框架生态中,FastAPI 凭借其极高的性能、原生的异步支持以及自动生成交互式 API 文档的特性,迅速成为了开发者的心头好。这篇文章将带你快速上手 FastAPI,并将其优雅地打包进 Docker 容器中,实现随处运行。

为什么选择 FastAPI?

  1. 高性能:基于 Starlette 和 Pydantic,性能可与 NodeJS 和 Go 媲美。
  2. 开发效率高:类型提示(Type Hints)不仅带来了优秀的代码补全体验,还能自动进行数据验证。
  3. 自带文档:开箱即用的 Swagger UI 和 ReDoc,极大降低了前后端沟通成本。

第一步:编写 FastAPI 应用

首先,我们需要一个最基础的 FastAPI 应用。新建一个项目目录,并在其中创建 requirements.txtmain.py

requirements.txt

fastapi>=0.100.0
uvicorn[standard]>=0.23.0
pydantic>=2.0.0

main.py

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="My First FastAPI App")

# 定义一个数据模型用于接收 POST 请求
class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None

@app.get("/")
async def read_root():
    return {"message": "Hello, FastAPI!"}

@app.post("/items/")
async def create_item(item: Item):
    # Pydantic 会自动验证传入的 JSON 数据是否符合 Item 模型
    item_dict = item.model_dump()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict

在本地你可以通过 uvicorn main:app --reload 运行并访问 http://127.0.0.1:8000/docs 查看自动生成的 API 文档。

第二步:编写 Dockerfile

为了让服务在任何服务器上都能稳定运行,我们将使用 Docker 进行容器化。在同级目录下创建 Dockerfile

# 使用官方轻量级 Python 镜像
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 复制依赖文件并安装
COPY requirements.txt .
# 使用阿里云镜像源加速安装(可选,适合国内网络环境)
RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/

# 复制项目代码
COPY . .

# 暴露 8000 端口
EXPOSE 8000

# 启动 FastAPI 服务
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

第三步:构建与运行

在终端中执行以下命令,将你的应用打包成镜像并运行:

# 构建镜像
docker build -t my-fastapi-app .

# 运行容器,将宿主机的 8080 端口映射到容器的 8000 端口
docker run -d --name fastapi-container -p 8080:8000 my-fastapi-app

现在,你的 FastAPI 服务已经安稳地运行在 Docker 容器中了。你可以通过 http://localhost:8080/docs 访问它。这种标准化的部署方式非常适合后续通过反向代理(如 Nginx)对外暴露服务。