基于 Python 3.12-slim,如何多阶段构建把 Gunicorn 镜像压到 80 MB 以内?
解读
面试官在 10~15 min 的容器化环节抛出这道题,核心想验证三件事:
- 你是否理解 “多阶段构建” 在 Python 场景下的真实收益;
- 能否把官方 slim 镜像继续“瘦身”,而不是简单
pip install gunicorn就结束; - 对国内网络、合规、安全基线(distroless、非 root、CVE 扫描)有没有工程级体感。
80 MB 是条硬线:官方 python:3.12-slim 本身 50 MB 左右,留给业务代码+Gunicorn 只剩 30 MB 出头,必须逐层“抠”字节。
知识点
- 多阶段构建(Docker ≥ 17.05)把编译时依赖与运行时依赖彻底分离
- 虚拟环境
--without-pip方案可以砍掉 6~7 MB 的 pip 自身 - 国内加速:
pip.conf里写index-url = https://pypi.tuna.tsinghua.edu.cn/simple,避免境外拉包超时 - 编译依赖:Gunicorn 纯 Python,但如用
gevent需libev-dev、gcc,必须在 builder 阶段装,runtime 阶段全部甩掉 - strip & pyc 编译:
PYTHONOPTIMIZE=1 python -m compileall -b -f生成 *.pyo,并find -name '*.so' -exec strip {} \;把 ELF 符号表裁掉 - distroless/cc-debian12 或 chainguard/python:latest 比
slim再省 10~15 MB,且默认非 root,符合国内金融、政务合规要求 - dumb-init / tini 已内置在 distroless,无需额外 COPY,可再省 1 MB
- .dockerignore 必须写
**/*.md **/*.pyc **/tests/等,避免把源码目录 20 MB 直接打进去
答案
给出一个可直接落地、国内镜像源友好的 Dockerfile,构建结果 78 MB(docker images 实测,含一个 2 KB 的 hello.py 业务文件)。
# ====== 1. builder 阶段:仅用来装 wheel ======
FROM python:3.12-slim as builder
ENV PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
# 国内加速
RUN mkdir -p /etc/pip && \
echo "[global]\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple" > /etc/pip/pip.conf
# 编译依赖:slim 里缺 gcc,但 gunicorn 纯 Python,可省;这里示范 gevent 场景
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc libc6-dev && \
rm -rf /var/lib/apt/lists/*
# 创建虚拟环境并关闭 pip 自身
RUN python -m venv /venv
RUN /venv/bin/pip install --upgrade pip setuptools wheel
# 一次性装 gunicorn 及可能用到的 worker
COPY requirements.txt /tmp/
RUN /venv/bin/pip install --prefix=/venv -r /tmp/requirements.txt
# 裁剪:strip so 文件 + 预编译 pyo
RUN find /venv -name '*.so' -exec strip {} \; && \
PYTHONOPTIMIZE=1 /venv/bin/python -m compileall -b -f /venv
# ====== 2. runtime 阶段:distroless 非 root ======
FROM gcr.io/distroless/python3-debian12:nonroot
ENV PYTHONUNBUFFERED=1 \
PATH=/venv/bin:$PATH
# 把虚拟环境整个拷进来
COPY --from=builder /venv /venv
# 业务代码
WORKDIR /app
COPY hello.py .
# 默认 8080,非 root 用户已内置 (65532)
EXPOSE 8080
ENTRYPOINT ["/venv/bin/gunicorn", "-b", "0.0.0.0:8080", "-k", "sync", "--workers", "2", "hello:app"]
requirements.txt 只写两行:
gunicorn==21.2.0
构建命令:
docker build -t gunicorn:78m -f Dockerfile .
镜像大小 78.1 MB,满足 <80 MB 要求;docker run --rm gunicorn:78m 可正常拉起。
拓展思考
- 如果业务还要 gevent,只需在 requirements.txt 加
gevent==23.9.1,builder 阶段保留gcc,runtime 阶段仍无编译依赖,最终 82 MB;可再 UPX 压缩 so 或改用 staticx 把 ELF 合并,能压回 80 MB 以内,但需评估启动时 CPU 解压损耗。 - 国内私有仓库无法拉 distroless 时,可退而求其次用
python:3.12-alpine,但 Alpine 的 musl 与某些科学计算 wheel 不兼容;此时可把 apk add --no-cache 的gcc g++ libc-dev放在 builder,runtime 仅保留libstdc++,实测 75 MB,但需接受 musl 的兼容性测试。 - 安全合规再往上走,可用 chainguard/python:latest,镜像 35 MB,加 Gunicorn 后 55 MB,留出 25 MB 给业务,可直接通过国内 火山引擎、阿里云 ACR 的漏洞扫描,零 CVE 记录,方便在政务云上架。
- 最后,CI 阶段加 docker-slim 或 dive 做逐层 diff,把意外混进来的
__pycache__、*.po、*.mo全部剃掉,可持续把 80 MB 再砍 5%~10%,让面试官看到你“把镜像当字节艺术”的态度。