如何维护含公共步骤的多个不同源Docker镜像 避免步骤重复?
Docker多镜像统一公共步骤的实现方案
以下是三种生产环境常用的落地方案,可根据你的镜像规模、构建流程灵活选择:
方案1:公共中间镜像层封装(推荐,适合大规模镜像场景)
把公共步骤提前构建为对应上游源镜像的中间层,所有业务镜像直接基于中间层构建,公共步骤仅需维护一份:
- 编写公共步骤的通用Dockerfile模板
Dockerfile.common:
# 上游基础镜像通过构建参数动态传入 ARG BASE_IMAGE FROM ${BASE_IMAGE} # 统一配置代理环境变量 ENV http_proxy=http://your-proxy:port \ https_proxy=http://your-proxy:port \ no_proxy=localhost,127.0.0.1,internal-domain.com # 拷贝根证书 COPY ./internal-root-ca.crt /usr/local/share/ca-certificates/ # 统一安装apt、pip通用依赖,更新证书 RUN apt update && apt install -y --no-install-recommends ca-certificates curl wget git \ && update-ca-certificates \ && pip install --upgrade pip setuptools wheel \ && apt clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
- 批量构建对应不同上游源的中间镜像:
# 构建基于source1的公共中间镜像 docker build -f Dockerfile.common --build-arg BASE_IMAGE=source1:v1.0 -t common-source1:latest . # 构建基于source2的公共中间镜像 docker build -f Dockerfile.common --build-arg BASE_IMAGE=source2:v2.3 -t common-source2:latest . # 构建基于source3的公共中间镜像 docker build -f Dockerfile.common --build-arg BASE_IMAGE=source3:v1.5 -t common-source3:latest .
- 原有业务Dockerfile仅需修改基础镜像引用即可,专属步骤无需调整:
# 原写法:FROM source1:v1.0 FROM common-source1:latest # 原有专属步骤保持不变 RUN foo
优势:缓存利用率高,公共步骤修改后仅需重新构建中间镜像,所有业务镜像下次构建自动生效,维护成本极低
方案2:公共步骤抽为Shell脚本注入(适合中小规模镜像场景)
把所有公共步骤封装为独立的Shell脚本,各个业务Dockerfile仅需添加固定几行调用脚本即可:
- 编写公共初始化脚本
common-init.sh:
#!/bin/bash set -e # 配置代理 export http_proxy=http://your-proxy:port export https_proxy=http://your-proxy:port # 安装证书、通用依赖 cp /tmp/internal-root-ca.crt /usr/local/share/ca-certificates/ apt update && apt install -y --no-install-recommends ca-certificates curl wget git update-ca-certificates pip install --upgrade pip setuptools wheel apt clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
- 业务Dockerfile调整如下:
FROM source1:v1.0 # 固定调用公共初始化脚本 COPY common-init.sh internal-root-ca.crt /tmp/ RUN chmod +x /tmp/common-init.sh && /tmp/common-init.sh # 原有专属步骤保持不变 RUN foo
优势:无需提前构建中间镜像,公共逻辑修改后所有业务镜像重新构建自动生效,实现简单
方案3:BuildKit INCLUDE语法复用Dockerfile片段(适合Docker版本较新的场景)
Docker 18.09+默认支持的BuildKit提供了INCLUDE扩展语法,可以直接把公共Dockerfile片段引入到各个业务Dockerfile中:
- 编写公共Dockerfile片段
Dockerfile.common:
ENV http_proxy=http://your-proxy:port \ https_proxy=http://your-proxy:port COPY ./internal-root-ca.crt /usr/local/share/ca-certificates/ RUN apt update && apt install -y --no-install-recommends ca-certificates curl wget git \ && update-ca-certificates \ && pip install --upgrade pip setuptools wheel \ && apt clean && rm -rf /var/lib/apt/lists/*
- 业务Dockerfile调整如下:
# 开启BuildKit扩展语法支持 # syntax = docker/dockerfile:1.4 FROM source1:v1.0 # 直接引入公共步骤片段 INCLUDE +Dockerfile.common # 原有专属步骤保持不变 RUN foo
优势:无需额外维护Shell脚本,也不需要提前构建中间镜像,原生Docker语法支持,可读性最高
内容的提问来源于stack exchange,提问作者Hong Ooi
相关产品推荐
相关产品推荐

