Docker使用buildx来取代传统build并同时构建多架构镜像

简介

Docker更新了build流程,提供了全新的构建工具,原先的docker build命令已经被标记为@deprecated啦!是时候学习新的buildx工具,开始装逼啦努力追上时代啦~

1
2
# sudo pacman -S docker-buildx
sudo docker buildx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Usage:  docker buildx [OPTIONS] COMMAND

Extended build capabilities with BuildKit

Options:
--builder string Override the configured builder instance

Management Commands:
imagetools Commands to work on images in registry

Commands:
bake Build from a file
build Start a build
create Create a new builder instance
du Disk usage
inspect Inspect current builder instance
ls List builder instances
prune Remove build cache
rm Remove a builder instance
stop Stop builder instance
use Set the current builder instance
version Show buildx version information

Run 'docker buildx COMMAND --help' for more information on a command.

使用方法

其实吧,和普通的build相比,没啥区别,但是多了好多集成化的功能,请看示例:

1
2
3
4
5
sudo docker buildx build \
--platform $PLATFORM \
-t "$IMAGE:$TAG" \
-t "$IMAGE:latest" \
--pull --push .

可以看到,pull(始终拉取新镜像,指FROM里的内容),push(自动build后push),platform(新增多架构构建),还是有着节省行数的好处的(

另外,x86的机器上也可以直接构建arm镜像啦,这里使用树莓派常用的arm64(也就是aarch64)举例,首先我们要建立一个buildx环境:

1
2
3
4
5
sudo docker buildx create \
--name multi_platform \
--use --platform \
linux/amd64,linux/arm64 \
--driver docker-container

然后用ls命令即可看到这个环境支持的架构:

1
sudo docker buildx ls
1
2
3
4
5
NAME/NODE         DRIVER/ENDPOINT             STATUS  BUILDKIT             PLATFORMS
multi_platform * docker-container
multi_platform0 unix:///var/run/docker.sock running v0.12.5 linux/amd64*, linux/arm64*, linux/amd64/v2, linux/amd64/v3, linux/amd64/v4, linux/386
default docker
default default running v0.11.7+d3e6c1360f6e linux/amd64, linux/amd64/v2, linux/amd64/v3, linux/amd64/v4, linux/386

可以看到,后面有些奇怪的东西,x86怎么还有v2、v3、v4,这激发了我的好奇心,搜索发现,其实是指令集更新的区别,这里Golang给的最直观:

来自:https://go.dev/wiki/MinimumRequirements

1
2
3
4
GOAMD64=v1 (default): The baseline. Exclusively generates instructions that all 64-bit x86 processors can execute.
GOAMD64=v2: all v1 instructions, plus CMPXCHG16B, LAHF, SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3.
GOAMD64=v3: all v2 instructions, plus AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, OSXSAVE.
GOAMD64=v4: all v3 instructions, plus AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL.

检测

关于自己的发行版目前支持的指令集,可以用以下命令查看:

1
/lib/ld-linux-x86-64.so.2 --help | grep "x86-64-v"
1
2
3
x86-64-v4 (supported, searched)
x86-64-v3 (supported, searched)
x86-64-v2 (supported, searched)

还有不少人(Gentoo狂热者?)把自己电脑里所有程序都改成v4构建的,以提高性能,Ubuntu文档里就有这样说:

https://cn.ubuntu.com/blog/optimising-ubuntu-performance-on-amd64-architecture_cn

还有Arch系的大佬介绍:

https://blog.chyk.ink/2022/08/11/arch-linux-upgrade-to-x86-64-v3-microarchitecture/

视频演示

B站:https://www.bilibili.com/video/BV14A4m1V7zT/