Docker v17.05开始支持多阶段构建 (multistage builds),能有效减少images的大小,本文以golanghelloword为例,演示Docker 多阶段构建。
golang helloword
- helloworld.go
package main
import "fmt"
func main(){
fmt.Printf("Hello World!");
}传统构建
- Dockerfile.one
FROM golang:1.11.10-alpine
WORKDIR /go/src/github.com/xiexianbin/go-helloworld/
ADD helloworld.go .
RUN GOOS=linux go build helloworld.go \
&& cp helloworld /root
WORKDIR /root/
CMD ["./helloworld"]- 构建命令
docker build -t xiexianbin/go-helloworld:1 -f Dockerfile.one .多阶段构建
- Dockerfile
FROM golang:1.11.10-alpine as builder
WORKDIR /go/src/github.com/xiexianbin/go-helloworld/
ADD helloworld.go .
RUN GOOS=linux go build helloworld.go
FROM alpine:latest as prod
WORKDIR /root/
COPY --from=0 /go/src/github.com/xiexianbin/go-helloworld/helloworld .
CMD ["./helloworld"]- 构建命令
docker build -t xiexianbin/go-helloworld:2 -f Dockerfile .构建后镜像对比
➜ dockerfile docker images | grep helloworld
xiexianbin/go-helloworld 1 9fe54345596b 3 seconds ago 315MB
xiexianbin/go-helloworld 2 777d49ca77c6 About a minute ago 7.53MB可以发现,采用多阶段构建时,镜像明显较小。
已有镜像的压缩(Squash)
多阶段构建解决的是"构建期"的体积问题;如果面对的是一个已经构建好的臃肿镜像,或需要抹掉历史层中残留的敏感信息(密码、密钥、临时文件),可以对镜像做 Squash,将多个层合并为一个层,从而减小体积并隐藏中间构建步骤。
docker-squash 独立工具
docker-squash 是一个第三方 Python 工具,可以直接操作已经构建好的镜像。它是 CLI 工具,推荐用 pipx 安装到独立虚拟环境,避免污染系统 Python:
pipx install docker-squash
# 或在 venv 中: python3 -m pip install docker-squash假设有一个原始镜像 my-app:raw,压缩并打上新标签 my-app:squashed:
docker-squash -t my-app:squashed my-app:raw该工具会自动导出镜像、合并多个层,然后再重新导入本地 Docker 环境。默认会保留基础镜像的层,只合并其上的层;也可以用 -f(--from)显式指定从哪一层/镜像开始合并:
# 从 ubuntu:20.04 基础镜像层之后开始合并
docker-squash -f ubuntu:20.04 -t my-app:squashed my-app:rawdocker build –squash 原生参数(实验特性)
Docker 经典 builder 内置了 --squash 构建参数,可以在 docker build 时直接压缩本次 Dockerfile 新增的层(基础镜像层不受影响,且构建缓存会被保留)。它是 daemon 级实验特性,需要在 /etc/docker/daemon.json(Linux)或 Docker Desktop 的 Docker Engine 设置中开启:
{
"experimental": true
}保存后重启 Docker 服务:
sudo systemctl restart dockerdocker build --squash -t my-app:latest .[!WARNING]
--squash依赖经典(legacy)builder,BuildKit 不支持该参数。Docker 23+ 默认启用 BuildKit,需要DOCKER_BUILDKIT=0 docker build --squash ...才能生效;且经典 builder 已被官方标记为 deprecated(仅 Windows 容器构建等场景保留)。官方文档明确建议:多数场景下多阶段构建是比 squash 更好的替代方案。
export / import 压平
这是一种传统的"压平"手段,会把整个镜像压成毫无历史记录的单一层。注意:它会丢失镜像的所有元数据(ENV、ENTRYPOINT、CMD、EXPOSE 等),因此压缩后需要重新指定:
# 1. 基于目标镜像创建临时容器(create 不会启动进程,无需依赖镜像的 ENTRYPOINT)
docker create --name temp-container my-app:raw
# 2. 将容器文件系统导出为 tar,再 import 为单一层的新镜像
# 可用 --change 重新注入部分元数据
docker export temp-container | docker import \
--change 'ENV APP_ENV=production' \
--change 'CMD ["./myapp"]' \
- my-app:squashed
# 3. 清理临时容器
docker rm temp-container如果不使用 --change,也可以写一个新的 Dockerfile,以压平后的镜像为基础镜像并补上 CMD/ENTRYPOINT。
方案选型
| 场景 | 推荐方案 |
|---|---|
| 正在编写 Dockerfile | 多阶段构建(Multi-stage Builds),无需实验特性与第三方工具 |
| 构建期必须压平新增层 | DOCKER_BUILDKIT=0 + docker build --squash(接受 legacy builder 与实验特性风险) |
| 处理别人打包好的、已臃肿的现有镜像 | docker-squash 二次压缩 |
| CI 中产出彻底重置历史的制品 | docker export / docker import(注意补回元数据) |