为什么 macos(x86) 运行 docker arm container arm64v8/alpine?

Why can macos(x86) run docker arm container arm64v8/alpine?

我碰巧发现我的 macos(x86) 可以 运行 一个 docker 手臂图像容器 arm64v8/alpine,但有以下警告:

docker run -it  arm64v8/alpine uname -a

WARNING: The requested image's platform (linux/arm64) does not match the detected host platform (linux/amd64) and no specific platform was requested
Linux d5509c57dd24 4.19.121-linuxkit #1 SMP Tue Dec 1 17:50:32 UTC 2020 aarch64 Linux

而且我很确定该图像不是多架构图像 (docker manifest inspect --verbose arm64v8/alpine)。为什么x86可以运行一个arm容器?

你是对的,图像不是多架构的,但是,docker可以运行。这背后的原因是一个名为 binfmt_misc 的内核子系统,它允许将二进制文件的 magic 编号设置为执行它们的特定操作。你可以在这个不错的 wikipedia post 中阅读更多关于它的内容。

Docker for Mac 即将到来,为 binfmt 魔法做好准备,因此无需执行任何操作即可启用它。它将在安装时开箱即用,您需要做的就是获取图像和 运行。该机制的详细信息可以在 docker-for-mac 项目的存储库中找到 link.

为了简单的解释,二进制图像有 magic 编号,允许内核决定如何处理执行。当 binfmt_misc 截获一个他识别出 magic 数字的文件时,他将调用与 magic 数字关联的处理程序。

仅此还不足以 运行 容器。 magic 的下一部分是 QEMU,它是各种 CPU 架构的模拟器。内核 (binfmt_misc) 将为每个 ARM64 二进制文件调用查询,并将模拟 ARM64v8。

这不仅限于 docker,也不限于在 macOS 上 运行 连接 docker 的虚拟 mac 网络。任何 linux 系统都可以配置为执行此操作。

您可以使用以下设置将其安装 Ubuntu 到 运行 仿真。

sudo apt-get install qemu binfmt-support qemu-user-static # Install the qemu packages
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes # This step will execute the registering scripts

docker run --rm -t arm64v8/ubuntu uname -m # Testing the emulation environment

有关整个设置过程的更多详细信息,请参阅 qemu-user-static 存储库

OP: If you are wondering what is the usefulness of this, from my personal experiance, I am using this functionality heavily when porting applications from X86 to other architectures (mainly ARM64). This allows me to run build systems for various architectures without having a physical machine on which I can run the build.