如何在已经存在的Docker容器上运行命令? [英] How do I run a command on an already existing Docker container?

查看:1348
本文介绍了如何在已经存在的Docker容器上运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含 -d 的容器,所以它不是互动的。

I created a container with -d so it's not interactive.

docker run -d shykes/pybuilder bin/bash

我看到容器已经退出: / p>

I see that the container has exited:

CONTAINER ID        IMAGE                     COMMAND             CREATED             STATUS                      PORTS               NAMES
d6c45e8cc5f0        shykes/pybuilder:latest   "bin/bash"          41 minutes ago      Exited (0) 2 seconds ago                        clever_bardeen

现在我想在机器上运行偶尔的命令并退出。只是为了得到回应。

Now I would like to run occasional commands on the machine and exit. Just to get the response.

我尝试启动机器。我试着附上我以为可以使用一个容器调用运行,但这似乎不允许。使用开始似乎运行然后快速存在。

I tried to start the machine. I tried attaching. I thought I could call run with a container, but that does not seem to be allowed. Using start just seems to run and then exist quickly.

我想要回到交互模式退出。

I'd like to get back into interactive mode after exiting.

我试过:

docker attach d6c45e8cc5f0

但是我得到:

2014/10/01 22:33:34 You cannot attach to a stopped container, start it first

但是如果我启动它,它会退出。抓住22.我不能赢。

But if I start it, it exits anyway. Catch 22. I can't win.

推荐答案

2014年10月,命令 https://docs.docker。 com / engine / reference / commandline / exec /

In October 2014 the Docker team introduced docker exec command: https://docs.docker.com/engine/reference/commandline/exec/

所以现在你可以在运行的容器中运行任何命令,只要知道它的ID(或名称):

So now you can run any command in a running container just knowing its ID (or name):

docker exec -it <container_id_or_name> echo "Hello from container!"

请注意, exec 运行容器如果容器当前已停止,则需要先运行以下命令:

Note that exec command works only on already running container. If the container is currently stopped, you need to first run it with the following command:

docker run -it -d shykes/pybuilder /bin/bash

这里最重要的是 -d 选项,代表分离。这意味着您最初提供给容器的命令( / bin / bash )将在后台运行,容器不会立即停止 。

The most important thing here is the -d option, which stands for detached. It means that the command you initially provided to the container (/bin/bash) will be run in the background and the container will not stop immediately.

这篇关于如何在已经存在的Docker容器上运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆