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

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

问题描述

我用 -d 创建了一个容器,所以它不是交互式的.

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

docker run -d shykes/pybuilder bin/bash

我看到容器已经退出:

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.

我试图启动机器.我尝试附加.我以为我可以用容器调用 run ,但这似乎是不允许的.使用 start 似乎只是运行然后快速存在.

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

但是如果我启动它,它无论如何都会退出.Catch 22.我赢不了.

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

推荐答案

2014 年 10 月 Docker 团队引入了 docker exec 命令: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 选项,它代表 detached.这意味着您最初提供给容器的命令 (/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天全站免登陆