且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在docker映像的新容器中运行bash?

更新时间:2023-11-24 21:35:40

如果您在不附加tty的情况下 docker run ,并且仅调用 bash ,则bash不会找到任何内容做,它退出.这是因为默认情况下,容器是非交互式的,并且以非交互式模式运行的shell希望脚本能够运行.如果没有,它将退出.

If you docker run without attaching a tty, and only call bash, then bash finds nothing to do, and it exits. That's because by default, a container is non-interactive, and a shell that runs in non-interactive mode expects a script to run. Absent that, it will exit.

要运行一个一次性的新容器,您只需附加一个tty和标准输入即可:

To run a disposable new container, you can simply attach a tty and standard input:

docker run --rm -it --entrypoint bash <image-name-or-id>

或者为防止处置上述容器,请在没有-rm 的情况下运行它.

Or to prevent the above container from being disposed, run it without --rm.

或者要输入正在运行的容器,请改用 exec :

Or to enter a running container, use exec instead:

docker exec -it <container-name-or-id> bash


在您询问的评论中


In comments you asked

您知道这和 docker run -it --entrypoint bash docker/whalesay 有什么区别吗?

在上面的两个命令中,您要指定 bash 作为 CMD .在此命令中,您将 bash 指定为 ENTRYPOINT .

In the two commands above, you are specifying bash as the CMD. In this command, you are specifying bash as the ENTRYPOINT.

每个容器都使用 ENTRYPOINT CMD 的组合来运行.如果您(或图像)未指定 ENTRYPOINT ,则默认入口点为/bin/sh -c .

Every container is run using a combination of ENTRYPOINT and CMD. If you (or the image) does not specify ENTRYPOINT, the default entrypoint is /bin/sh -c.

因此,在前面的两个命令中,如果以 CMD 身份运行 bash ,并且使用默认的 ENTRYPOINT ,则容器将使用

So in the earlier two commands, if you run bash as the CMD, and the default ENTRYPOINT is used, then the container will be run using

/bin/sh -c bash

如果您指定-entrypoint bash ,则它将运行

If you specify --entrypoint bash, then instead it runs

bash <command>

其中< command> 是图像中指定的 CMD (如果已指定).

Where <command> is the CMD specified in the image (if any is specified).