FROM ubuntu:22.04
COPY . /app
RUN apt-get update && apt-get install -y python3 python3-pip
RUN pip install -r /app/requirements.txt
WORKDIR /app
CMD ["python3", "app.py"]
这个镜像可能 1GB+。问题:每改一行代码,pip install 那层缓存就失效。
# 阶段1:构建依赖
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
# 阶段2:运行时(只复制需要的)
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY app.py .
CMD ["python3", "app.py"]
# 好:requirements.txt 不变就用缓存
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
# 差:每次改代码都重装依赖
COPY . .
RUN pip install -r requirements.txt
| 镜像 | 大小 | 适合 |
|---|---|---|
| python:3.11 | ~1GB | 不推荐 |
| python:3.11-slim | ~150MB | 推荐 |
| python:3.11-alpine | ~50MB | 更小,但有些 C 扩展编译麻烦 |
构建阶段用完整镜像装编译工具,运行阶段只复制编译好的产物,不保留编译器和源码。
# 差:3 层
RUN apt-get update
RUN apt-get install -y git
RUN rm -rf /var/lib/apt/lists/*
# 好:1 层
RUN apt-get update && apt-get install -y git \
&& rm -rf /var/lib/apt/lists/*
docker build -t myapp . # 构建
docker images # 看镜像大小
docker history myapp # 看每一层多大
docker run -p 8000:8000 myapp # 运行