> For the complete documentation index, see [llms.txt](https://coderlzw.gitbook.io/operation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coderlzw.gitbook.io/operation/cli/docker-compose/docker-compose-exec.md).

# docker compose exec

## 描述

* 在 **正在运行** 的容器里执行命令。
* 相当于 `docker exec`，但作用对象是 Compose 管理的服务 (service) 容器。
* 使用这个子命令，你可以在服务对应的容器里运行任意命令。
* 默认情况下，命令会分配一个 TTY (伪终端)，因此你可以像下面这样进入交互式 shell：

  ```bash
  docker compose exec web sh
  ```

  这样能获得一个交互式提示符。
* 默认行为：Compose 会进入交互模式并分配 TTY；而等效的 `docker exec` 命令如果要有这个行为，通常需要加 `--interactive --tty`。
* 同时，Compose 支持 `--interactive` 和 `--tty` 这些标志，以便在脚本里强制启用或禁用交互 / TTY 模式（例如 `--interactive=false` 可以在脚本中禁用交互）。

***

## 选项

| 选项                  | 默认值 / 说明           | 描述                                          |
| ------------------- | ------------------ | ------------------------------------------- |
| `-d, --detach`      | —                  | 分离 (detached) 模式：命令在后台运行，不附加当前终端。           |
| `-e, --env KEY=VAL` | —                  | 设置环境变量 (可以指定多个 `-e`)。                       |
| `--index`           | —                  | 如果服务有多个副本 (replicas)，可以指定执行命令的容器索引 (index)。 |
| `-T, --no-tty`      | `true` (默认会分配 TTY) | 禁用伪 TTY 分配。如果你不想要 TTY (例如在脚本里)，可以加这个选项。     |
| `--privileged`      | —                  | 给执行命令的进程扩展权限 (privileged 模式)。               |
| `-u, --user USER`   | —                  | 以指定用户身份在容器里运行命令。                            |
| `-w, --workdir DIR` | —                  | 指定在容器里执行命令时的工作目录 (workdir)。                 |

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://coderlzw.gitbook.io/operation/cli/docker-compose/docker-compose-exec.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.
