# Docker attach 命令

[Docker命令大全](/docker/manual/docker-command-manual.md)

`docker attach` 命令用于附加到正在运行的 Docker 容器的标准输入、输出和错误输出（stdin、stdout、stderr）。允许用户直接与容器交互，就像与正在运行的进程交互一样。

### 语法

docker attach \[OPTIONS] CONTAINER

**常用选项**

* `**--detach-keys**`: 设置一个在容器中分离的键序列（例如，`ctrl-c`）。
* `**--no-stdin**`: 不附加标准输入。
* `**--sig-proxy**`: 当键盘中断时，将信号代理到容器（默认为 true）。

### 实例

例：附加到名为 my\_container 的容器，用户可以直接与容器的标准输入、输出和错误输出交互。

```shell
docker attach my_container
```

例：附加到 my\_container 容器，但不附加标准输入。

```shell
docker attach --no-stdin my_container
```

例：附加到 my\_container 容器，并设置 ctrl-c 为分离键序列。

```shell
docker attach --detach-keys="ctrl-c" my_container
```

### 注意事项

* 如果附加到一个已经附加了其他会话的容器，所有会话将共享相同的标准输入、输出和错误输出。这意味着多个会话中的输出可能会混杂在一起。
* 使用 `docker attach` 进行交互时，需要注意正确设置分离键序列，以确保能够安全地分离而不停止容器。

### 常用场景

* **调试和故障排除**: 直接附加到正在运行的容器进行调试和故障排除。
* **监控**: 实时查看容器内的输出和日志。
* **交互操作**: 需要与容器内的应用程序进行交互时使用。

`docker attach` 命令是 Docker 中一个有用的命令，允许用户附加到正在运行的容器并与其交互。通过此命令，用户可以实时查看容器的输出，进行调试和故障排除，以及执行其他交互操作。使用适当的选项和分离键序列，可以灵活地管理和控制与容器的交互。

### attach与 exec -it 区别

| **功能点**     | **docker attach**            | **docker exec -it** |
| ----------- | ---------------------------- | ------------------- |
| **目标**      | 连接到容器的主进程                    | 在容器内启动一个新的进程        |
| **交互模式**    | 使用主进程的 STDIN、STDOUT 和 STDERR | 可启动交互式终端（如 bash/sh） |
| **对主进程的影响** | 可能干扰主进程                      | 不会干扰主进程             |
| **新进程支持**   | 不支持                          | 支持                  |
| **适用场景**    | 查看容器启动日志，直接交互主进程             | 调试、执行命令或管理容器环境      |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tuonioooo-notebook.gitbook.io/docker/manual/docker-attach-command.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
