Skip to content
赞赏-微信扫码

构建发布-FastAPI应用

容器镜像,是分层构建的。不容易变动的层,写到 Dockerfile 的靠前位置。

构建镜像

需要一个 Makefile 和 一个 Dockerfile 来构建镜像。

Makefile
.PHONY: build env

VERSION = 1.0.0

build: Dockerfile
	buildctl \
	--addr tcp://buildkitd.cicd.svc.cluster.local:1234 \
	build \
	--frontend dockerfile.v0 \
	--local context=. \
	--local dockerfile=. \
	--output type=image,name=hb.apihub.net/apihub.net/open:$(VERSION),push=true
env:
	pip install -i https://mirrors.apihub.net/repository/pypi/simple -r requirements.txt
Dockerfile
FROM hb.apihub.net/python:3.12-slim-bookworm

RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' > /etc/timezone
RUN export LANG="C.UTF-8"

WORKDIR /app

COPY requirements.txt .
RUN pip install -i https://mirrors.apihub.net/repository/pypi/simple -r requirements.txt

COPY . /app

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
.dockerignore
.git/
.gitignore
.vscode/
.idea/
__pycache__/
logs/
Makefile
Dockerfile
README.md

python 项目中,通常会在根路径放一个 requirements.txt

Makefile 里,写了一个 env 指令,可以在空白的开发容器里,快速初始化依赖。

Dockerfile 中有个关键步骤值得说一下。requirements.txt 单独先复制到容器内,然后执行 pip 命令。如果依赖文件里的内容没有改变,pip 命令这一行构建过程是可以被缓存下来的。可以体验到 1秒 构建完的快感,增量拉取的新镜像也只有 python 源码那 几K 文本的大小。

最大请求体大小

fastapi 默认是没有限制 http 请求体大小的。这会是一个安全隐患。随便手动调下接口,传个超大的请求体,就能轻松消耗服务器内存。

参考 流量入口 章节中的 ip 白名单限流 的配置,在 ingress 上处理最大请求体大小限制。