问题背景
在使用 macos 在 m4 处理器的Docker 进行多平台构建时,经常会遇到以下两种错误:
- 多平台构建不支持错误:
ERROR: Multi-platform build is not supported for the docker driver.
Switch to a different driver, or turn on the containerd image store, and try again.
2. 执行格式错误(当不使用 --driver docker-container 时):
ERROR: failed to solve: failed to compute cache key: failed to get stream processor for application/vnd.docker.image.rootfs.diff.tar.gzip: fork/exec /usr/bin/unpigz: exec format error
错误原因分析
第一个错误的原因
- Docker 默认驱动不支持多平台构建
- 需要使用支持多平台的构建驱动
第二个错误的原因
- 当使用非
docker-container驱动时,构建过程中会尝试在当前系统上执行目标平台的二进制文件 - 例如在 x86_64 系统上构建 ARM64 镜像时,系统尝试执行 ARM64 格式的
/usr/bin/unpigz - 由于架构不匹配,导致 "exec format error" 错误
解决方案
方案一:使用 docker-container 驱动(推荐)
去掉勾选后执行:
# 1. 创建新的构建器实例,使用 docker-container 驱动
docker buildx create --name multiplatform --driver docker-container --use
# 2. 启动并检查构建器
docker buildx inspect --bootstrap
# 3. 验证构建器支持的平台
docker buildx inspect
# 4. 执行多平台构建
docker buildx build --platform linux/amd64,linux/arm64 -t your-image:tag .
# 5. 如果需要推送到仓库
docker buildx build --platform linux/amd64,linux/arm64 -t your-image:tag --push .
注意事项
docker-container驱动的优势:
-
- 完全隔离的构建环境
- 支持所有 BuildKit 功能
- 避免架构兼容性问题
- 性能考虑:
-
- 首次使用需要下载构建器镜像
- 跨架构构建可能较慢,建议使用缓存
- 缓存策略:
# 使用缓存优化构建速度
docker buildx build \
--platform linux/amd64,linux/arm64 \
--cache-from type=registry,ref=myregistry/myapp:cache \
--cache-to type=registry,ref=myregistry/myapp:cache,mode=max \
--push \
-t myregistry/myapp:latest .
通过使用 docker-container 驱动,可以彻底解决多平台构建中的各种兼容性问题,确保构建过程稳定可靠。