docker attach 和 docker exec 的区别 [英] difference between docker attach and docker exec
问题描述
两者都可以在容器中执行命令.两者都可以分离容器.
Both will be able to execute commands in container. Both could detach the container.
那么 docker exec 和 docker attach 之间的真正区别是什么?
So what is the real difference between docker exec and docker attach?
推荐答案
有一个 commit PR 添加到文档中:
There was a commit PR which added to the doc:
注意:此命令 (attach
) 不适用于在容器中运行新进程.请参阅:docker exec
.
Note: This command (
attach
) is not for running a new process in a container. See:docker exec
.
Docker 的答案.如何在运行的容器中获取 bashssh (run -d
)?" 说明了区别:
The answer to "Docker. How to get bashssh inside runned container (run -d
)?" illustrates the difference:
(docker >= 1.3) 如果我们使用 docker attach
,我们只能使用一个shell实例.
因此,如果我们想使用容器外壳的新实例打开新终端,我们只需要运行 docker exec
(docker >= 1.3) If we use
docker attach
, we can use only one instance of shell.
So if we want to open new terminal with new instance of container's shell, we just need to rundocker exec
如果docker容器是使用/bin/bash
命令启动的,你可以使用attach来访问它,如果不是那么你需要执行命令来创建一个bash使用 exec
在容器内的实例.
if the docker container was started using /bin/bash
command, you can access it using attach, if not then you need to execute the command to create a bash instance inside the container using exec
.
如这个问题中所述:
- Attach 不是为了在容器中运行额外的东西,而是为了附加到正在运行的进程.
- "
docker exec
" 专门用于在已经启动的容器中运行新事物,无论是外壳还是其他一些进程.
- Attach isn't for running an extra thing in a container, it's for attaching to the running process.
- "
docker exec
" is specifically for running new things in a already started container, be it a shell or some other process.
同样的问题补充:
虽然 attach
没有很好的命名,特别是因为 LXC 命令 lxc-attach
(它更类似于 docker exec
,但特定于 LXC),它确实有一个特定的目的,即从字面上将您附加到 Docker 启动的进程中.
根据进程的不同,行为可能会有所不同,例如附加到 /bin/bash
会给你一个 shell,但附加到 redis-server 会像你'd 只是直接启动了 redis,没有进行守护进程.
While
attach
is not well named, particularly because of the LXC commandlxc-attach
(which is more akindocker exec <container> /bin/sh
, but LXC specific), it does have a specific purpose of literally attaching you to the process Docker started.
Depending on what the process is the behavior may be different, for instance attaching to/bin/bash
will give you a shell, but attaching to redis-server will be like you'd just started redis directly without daemonizing.
这篇关于docker attach 和 docker exec 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!