多阶段构建

Docker 进阶

Mike Metzger

Data Engineering Consultant

单阶段构建

  • 典型的 Docker 镜像用单个 FROM 命令创建
  • 每次在基础镜像上添加内容都会增大体积并增加管理难度
  • 设想一个在使用前需编译的应用
    • 您可以将所需组件都加入镜像,编译后再配置最终镜像
    • 即使未使用,镜像中也常会残留多余内容
FROM ubuntu
RUN apt update
RUN apt install gcc -y
...
RUN make
CMD ["data_app"]
Docker 进阶

多阶段构建

  • 多阶段构建使用多个容器
  • 通常包含一个或多个构建阶段
  • 将最终组件复制到最终镜像中
  • 构建阶段随后会自动移除
    • 节省空间,缩小镜像体积
  • 在 Dockerfile 中需要额外语法
    • AS <alias>
    • COPY --from=<alias>
Docker 进阶

多阶段构建示例

# Create initial build stage
FROM ubuntu AS stage1

# Install compiler and compile code RUN apt install gcc -y ... RUN make
# Start new stage to create final image FROM alpine-base
# Copy from first stage to final COPY --from=stage1 /data_app /data_app
# Run application on container start CMD ["data_app"]
Docker 进阶

让我们来练习!

Docker 进阶

Preparing Video For Download...