0%

使用 docker buildx 构建多 CPU 架构镜像

使用 docker buildx 构建多 CPU 架构镜像

docker 版本大于等于 19.03 支持使用 docker buildx 方式构建多 CPU 架构镜像

启动 docker buildx

在最新的 docker 20.10.7 版本中,docker buildx 已经默认启动,可以通过 docker buildx version 查看。

1
2
root@:~# docker buildx version
github.com/docker/buildx v0.5.1-docker 11057da37336192bfc57d81e02359ba7ba848e4a

如果返回找不到命令,那么需要为当前版本 docker 开启这项功能。编辑 /etc/docker/daemon.json 文件,写入 "experimetal": true,保存退出后重启 docker。

1
2
3
# 请备份 daemon.json 文件!!!
echo "{"experimetal": true}" > /etc/docker/daemon.json;
systemctl restart docker

开启 binfmt_misc

通过一个特权容器来开启 Linux 系统上的 binfmt_misc

1
docker run --rm --privileged docker/binfmt:a7996909642ee92942dcd6cff44b9b95f08dad64

DockerHub 地址: docker/binfmt

查看是否设置正确

1
2
3
4
5
6
7
8
9
10
11
root@:~# ls -al /proc/sys/fs/binfmt_misc/
total 0
drwxr-xr-x 2 root root 0 Jul 7 06:27 .
dr-xr-xr-x 1 root root 0 Jul 7 06:08 ..
-rw-r--r-- 1 root root 0 Jul 7 06:27 qemu-aarch64
-rw-r--r-- 1 root root 0 Jul 7 06:27 qemu-arm
-rw-r--r-- 1 root root 0 Jul 7 06:27 qemu-ppc64le
-rw-r--r-- 1 root root 0 Jul 7 06:27 qemu-riscv64
-rw-r--r-- 1 root root 0 Jul 7 06:27 qemu-s390x
--w------- 1 root root 0 Jul 7 06:27 register
-rw-r--r-- 1 root root 0 Jul 7 06:27 status

切换镜像构建为多架构构建器

1
docker buildx create --use --name mybuilder

验证构建器是否生效

1
2
3
4
5
6
root@:~# docker buildx ls
NAME/NODE DRIVER/ENDPOINT STATUS PLATFORMS
mybuilder * docker-container
mybuilder0 unix:///var/run/docker.sock inactive
default docker
default default running linux/amd64, linux/386, linux/arm64, linux/riscv64, linux/ppc64le, linux/s390x, linux/arm/v7, linux/arm/v6

在 amd64 机器上启动 arm 架构容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
root@:~# docker pull --platform arm64 nginx
root@:~# docker run -d -p 80:80 --platform arm64 nginx
root@:~# curl localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>