feat: reduce image size

This commit is contained in:
Chenyme committed 2025-10-17 12:44:24 +08:00
1 parent 29d7b64f1c
commit 87cf2a5673
1 file changed
+12 -26
+12 -26
View File
@@ -1,46 +1,32 @@
# 构建阶段 - 使用完整镜像编译依赖
# 构建阶段
FROM python:3.11-slim AS builder
WORKDIR /build
# 安装编译工具
RUN apt-get update && \
apt-get install -y --no-install-recommends \
gcc \
g++ \
libffi-dev \
&& rm -rf /var/lib/apt/lists/*
# 安装依赖到独立目录
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install --compile -r requirements.txt
# 清理 Python 包中的冗余文件
RUN find /install -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true && \
RUN pip install --no-cache-dir --only-binary=:all: --prefix=/install -r requirements.txt && \
find /install -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true && \
find /install -type d -name "tests" -exec rm -rf {} + 2>/dev/null || true && \
find /install -type d -name "test" -exec rm -rf {} + 2>/dev/null || true && \
find /install -type d -name "*.dist-info" -exec sh -c 'rm -f "$1"/RECORD "$1"/INSTALLER' _ {} \; && \
find /install -type f -name "*.pyc" -delete && \
find /install -type f -name "*.pyo" -delete && \
find /install -type f -name "*.c" -delete && \
find /install -type f -name "*.h" -delete && \
find /install -type f -name "*.txt" -path "*/pip/*" -delete 2>/dev/null || true
find /install -name "*.so" -exec strip --strip-unneeded {} \; 2>/dev/null || true
# 运行阶段 - 使用最小镜像
FROM python:3.11-slim
WORKDIR /app
# 只安装必要的运行时库
RUN apt-get update && \
apt-get install -y --no-install-recommends \
libffi8 \
ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& rm -rf /tmp/* /var/tmp/* \
&& rm -rf /usr/share/doc/* \
&& rm -rf /usr/share/man/* \
&& rm -rf /var/cache/apt/*
# 清理基础镜像中的冗余文件
RUN rm -rf /usr/share/doc/* \
/usr/share/man/* \
/usr/share/locale/* \
/var/cache/apt/* \
/var/lib/apt/lists/* \
/tmp/* \
/var/tmp/*
# 从构建阶段复制已安装的包
COPY --from=builder /install /usr/local