From d386cc7180e11e3cbc0968f1dcb9df3c10ce2298 Mon Sep 17 00:00:00 2001 From: snaily Date: Thu, 18 Sep 2025 10:21:28 +0800 Subject: [PATCH] =?UTF-8?q?build(docker):=20=E4=BC=98=E5=8C=96=20Dockerfil?= =?UTF-8?q?e=20=E4=BB=A5=E5=AE=9E=E7=8E=B0=E5=A4=9A=E9=98=B6=E6=AE=B5?= =?UTF-8?q?=E6=9E=84=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 Dockerfile 修改为多阶段构建,以减小最终镜像的体积并提高构建效率。 第一阶段(builder)负责安装 Python 依赖项。 第二阶段创建最终的生产镜像,仅从构建器阶段复制已安装的依赖包和应用程序代码,不包含构建时的工具和缓存。 这种方法可以显著减小镜像大小,并利用 Docker 的层缓存机制,仅在 `requirements.txt` 发生变化时才重新安装依赖。 --- Dockerfile | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 1c36481..fff1123 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,29 @@ +# Stage 1: Build dependencies +FROM python:3.10-slim AS builder + +WORKDIR /app + +# Upgrade pip and setuptools +RUN pip install --upgrade pip setuptools + +# Copy and install requirements +# This layer is cached and only re-runs when requirements.txt changes +COPY ./requirements.txt /app/ +RUN pip install --no-cache-dir -r requirements.txt + +# Stage 2: Final application image FROM python:3.10-slim WORKDIR /app -# 复制所需文件到容器中 -COPY ./requirements.txt /app +# Copy installed packages from the builder stage +COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages + +# Copy the application code +COPY ./app /app/app COPY ./VERSION /app -RUN pip install --no-cache-dir -r requirements.txt -COPY ./app /app/app +# Set environment variables ENV API_KEYS='["your_api_key_1"]' ENV ALLOWED_TOKENS='["your_token_1"]' ENV TZ='Asia/Shanghai'