Skip to content

Commit d386cc7

Browse files
committed
build(docker): 优化 Dockerfile 以实现多阶段构建
将 Dockerfile 修改为多阶段构建,以减小最终镜像的体积并提高构建效率。 第一阶段(builder)负责安装 Python 依赖项。 第二阶段创建最终的生产镜像,仅从构建器阶段复制已安装的依赖包和应用程序代码,不包含构建时的工具和缓存。 这种方法可以显著减小镜像大小,并利用 Docker 的层缓存机制,仅在 `requirements.txt` 发生变化时才重新安装依赖。
1 parent bed3647 commit d386cc7

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

Dockerfile

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
1-
FROM python:3.10-slim
1+
# Stage 1: Build dependencies
2+
FROM python:3.10-slim AS builder
23

34
WORKDIR /app
45

5-
# 复制所需文件到容器中
6-
COPY ./requirements.txt /app
7-
COPY ./VERSION /app
6+
# Upgrade pip and setuptools
7+
RUN pip install --upgrade pip setuptools
88

9+
# Copy and install requirements
10+
# This layer is cached and only re-runs when requirements.txt changes
11+
COPY ./requirements.txt /app/
912
RUN pip install --no-cache-dir -r requirements.txt
13+
14+
# Stage 2: Final application image
15+
FROM python:3.10-slim
16+
17+
WORKDIR /app
18+
19+
# Copy installed packages from the builder stage
20+
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
21+
22+
# Copy the application code
1023
COPY ./app /app/app
24+
COPY ./VERSION /app
25+
26+
# Set environment variables
1127
ENV API_KEYS='["your_api_key_1"]'
1228
ENV ALLOWED_TOKENS='["your_token_1"]'
1329
ENV TZ='Asia/Shanghai'

0 commit comments

Comments
 (0)