在使用docker build的时候,有的时候需要构建非当前平台版本的镜像,比如我在arm的机器上构建x86的镜像,反之亦然。这时候传统的docker build命令就行不通了,需要使用buildx来支持构建多平台镜像。

1
docker buildx build --platform linux/arm64,linux/amd64 -t ubuntu-x11:18.04 .

执行这个命令的时候,可能会遇到如下输出(mac下的docker desktop)

1
2
3
4
5
❯ docker buildx build --platform linux/arm64,linux/amd64 -t ubuntu-x11:18.04 .
[+] Building 0.0s (0/0) docker:desktop-linux
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.
Learn more at https://docs.docker.com/go/build-multi-platform/

这个ERROR的含义是当前的docker builder不支持多平台镜像build,需要切换builder。

1
2
3
4
5
6
# 先创建一个新的 buildx builder,并指定 docker-container 作为驱动
docker buildx create --name mybuilder --use --driver docker-container
# 确保 buildx 处于正确状态
docker buildx ls
# 随后就可以正常 build 了
docker buildx build --platform linux/arm64,linux/amd64 -t ubuntu-x11:18.04 --push .

这里必须要给命令加上一个--push选项将镜像push到远端仓库或者本地仓库,因为buildx没有办法直接把镜像写入images中。如果需要push到dockerhub则需要先执行docker login登录一下。

1
2
WARNING: No output specified with docker-container driver. Build result will only remain in the build cache. To push result image into registry use --push or to load image into docker use --load
dockerfile:1

不过,后续我执行命令的时候一直因为dockerhub没有办法连上导致拉不下原始的镜像,麻了……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
❯ docker buildx build --platform linux/amd64 -t musnows/ubuntu-x11:18.04  --push  . 

[+] Building 30.8s (3/3) FINISHED docker-container:mybuilder
=> [internal] load build definition from dockerfile 0.0s
=> => transferring dockerfile: 1.88kB 0.0s
=> ERROR [internal] load metadata for docker.io/musnows/ubuntu:18.04 30.7s
=> [auth] musnows/ubuntu:pull token for registry-1.docker.io 0.0s
------
> [internal] load metadata for docker.io/musnows/ubuntu:18.04:
------
dockerfile:2
--------------------
1 | # this images is build from dockerfile.base
2 | >>> FROM musnows/ubuntu:18.04
3 |
4 | ARG DEBIAN_FRONTEND=noninteractive
--------------------
ERROR: failed to solve: musnows/ubuntu:18.04: failed to resolve source metadata for docker.io/musnows/ubuntu:18.04: failed to authorize: failed to fetch oauth token: Post "https://auth.docker.io/token": dial tcp [2a03:2880:f10d:183:face:b00c:0:25de]:443: i/o timeout

更新:发现了一篇博客提到了和我相同的错误,是因为之前创建builder的时候用了另外一个mybuilder,导致它识别不到我们的登录信息。所以需要使用默认的builder才能访问到认证信息,正常拉取容器。

使用下面俩命令切换回默认的builder

1
2
docker context use default
docker buildx use default

切换了之后就能正常构建了,不过还是没办法一次构建俩平台的镜像,又回到了原点……