多階段建置

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...