build(docker): 优化 Dockerfile 以实现多阶段构建

将 Dockerfile 修改为多阶段构建,以减小最终镜像的体积并提高构建效率。

第一阶段(builder)负责安装 Python 依赖项。
第二阶段创建最终的生产镜像,仅从构建器阶段复制已安装的依赖包和应用程序代码,不包含构建时的工具和缓存。

这种方法可以显著减小镜像大小,并利用 Docker 的层缓存机制,仅在 `requirements.txt` 发生变化时才重新安装依赖。
This commit is contained in:
snaily
2025-09-18 10:21:28 +08:00
parent bed3647424
commit d386cc7180

View File

@@ -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'