【问题标题】:Can't run docker container for a simple program无法为简单程序运行 docker 容器
【发布时间】:2019-02-12 20:50:34
【问题描述】:

我打算将 docker 用于 c++ 项目。 我添加了一个简单的 C++ 程序,它打印“hello world”来测试它。 然后我编译了它

g++ -o helloworldexecutable helloword.cpp

将 Dockerfile 添加到项目根文件夹 Dockerfile 包括:

FROM scratch
ADD helloworldexecutable / 
CMD helloworldexecutable

当我运行时:sudo docker build --tag helloworldexecutable . 它表明构建成功。我看到这张图片使用sudo docker images 我可以启动 sudo docker run hello-world 但运行 sudo docker run helloexecutable 我得到一个错误:

docker:来自守护进程的错误响应:OCI 运行时创建失败:container_linux.go:344:启动容器进程导致“exec:\”/bin/sh\“:stat /bin/sh:没有这样的文件或目录”:未知。

可能是什么问题?

【问题讨论】:

  • helloworldexecutable 可能没有执行权限。你也不需要像./helloworldexecutable那样在可执行文件前面加上./吗?
  • 它确实有执行权限。不,你没有
  • 它是动态链接的,但FROM scratch 图像不包含任何库,甚至不包含运行它所需的动态加载器。
  • 另外,如果你说CMD helloworldexecutable,Docker 会尝试运行/bin/sh -c 'helloworldexecutable',而FROM scratch 映像没有/bin/sh
  • @DavidMaze 虽然它没有修复根本问题,但您仍应添加您的评论作为答案,因为它直接回答了“为什么会发生此错误? "

标签: c++ docker dockerfile


【解决方案1】:

Cpp 文件:

#include <iostream>
using namespace std;

int main() 
{
    cout << "Hello, World!";
    return 0;
}

编译(关于--static标志的详细信息如下):

g++ -o helloworldexecutable --static helloword.cpp

Dockerfile:

FROM scratch
ADD helloworldexecutable / 
CMD ["/helloworldexecutable"]

结果:

$ docker build -t testcpp .
Sending build context to Docker daemon  2.254MB
Step 1/3 : FROM scratch
 ---> 
Step 2/3 : ADD helloworldexecutable /
 ---> Using cache
 ---> 0dd28bce4aed
Step 3/3 : CMD ["/helloworldexecutable"]
 ---> Running in 170a865b9527
Removing intermediate container 170a865b9527
 ---> 8a09e556c290
Successfully built 8a09e556c290
Successfully tagged testcpp:latest


$ docker container run --rm testcpp
Hello, World!$

来自Creating a Docker Image from Scratch

创建静态二进制文件

...但是大多数高级应用程序依赖于许多系统库(如 glibc、musl、klibc 等)和许多运行时依赖项,如 Python 或 Node.js 或 Java Runtime。应用程序二进制文件中没有所有可用的库,但是当它开始执行时,它会从主机操作系统调用这些库。

因为我们试图从头开始创建图像,所以我们不会得到这些细节。所以我们的应用需要是静态文件或者独立的可执行文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2017-11-03
    相关资源
    最近更新 更多