为什么这个程序运行在容器中而不运行在宿主机上?

Why does this program runs in a container but not on the host?

我正在做一个非常简单的 docker 图像,用一个 c++ 编写的程序来打招呼。

我必须从虚拟机构建可执行文件,Ubuntu 18.04,x86-64。

我在另一台机器上启动了这个可执行文件,通过 cmd Windows 10 64 位,但它抛出以下内容:

hello.exe n’est pas compatible avec la version de Windows actuellement exécutée. Vérifiez dans les informations système de votre ordinateur, puis contactez l’éditeur de logiciel.

(说它与这个 windows 版本不兼容)

当使用 git bash 启动它时,它抛出:

bash: ./hello.exe: cannot execute binary file: Exec format error

我原以为这个可执行文件不能从容器中运行,据我所知,它共享主机库。但令人惊讶的是,它确实有效:

$ docker run hello
Hello! This message is coming from a container

我想知道为什么它运行良好。我一定是哪里误解了什么。

docker文件:

FROM scratch
ADD hello.exe /
CMD ["/hello.exe"]

C++程序:

#include <iostream>
using namespace std;
int main()
{
    cout << "Hello! This message is coming from a container \n ";
    return 0;
}

用于构建可执行文件的 g++ 命令:

g++ -o hello.exe -static main.cpp

您的 Dockerfile 使用“scratch”图像,这是一个最小的图像(带有非常基本的二进制文件以减小大小)。

According to Docker Hub, the scratch image is Docker’s reserved empty image, which is useful in the context of building base images (such as debian and busybox) or super minimal images. As of Docker 1.5.0, FROM scratch is a no-op in the Dockerfile, and will not create an extra layer in our image. The FROM scratch command signals to the build process that we want the next command in the Dockerfile to be the first filesystem layer in our image.

FROM scratch
ADD hello.exe /
CMD ["/hello.exe"]

Scratch 是保留的空 linux 图像,可以 运行 linux 二进制文件。因为,你在 ubuntu 上编译你的程序,它可以 运行 在 linux 容器上而不是在你的 windows 机器上。

与其他用户一样,将扩展名更改为 .exe 不会使其成为 windows 可执行文件。

很好的解释:

进一步参考:https://codeburst.io/docker-from-scratch-2a84552470c8