> For the complete documentation index, see [llms.txt](https://yeasy.gitbook.io/docker_practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yeasy.gitbook.io/docker_practice/di-er-bu-fen-jin-jie-pian/11_compose/11.5_compose_file.md).

# 11.5 Compose 模板文件

模板文件是使用 `Compose` 的核心，涉及到的指令关键字也比较多。但大家不用担心，这里面大部分指令跟 `docker run` 相关参数的含义都是类似的。

默认的模板文件名称为 `compose.yaml`（也兼容 `docker-compose.yml` 等历史文件名），格式为 YAML。

本书同时维护一份可直接运行 `docker compose config` 校验的[完整 Compose 示例](https://github.com/yeasy/docker_practice/tree/master/examples/validated/compose/compose.yaml)。下面的围栏与该文件由测试强制保持一致；需要复制完整文件时，以任一处为准。

```yaml
name: docker-practice

services:
  web:
    image: nginx:1.28-alpine
    ports:
      - "8080:80"
    restart: unless-stopped
```

注意每个服务都必须通过 `image` 指令指定镜像或 `build` 指令（需要 Dockerfile）等来自动构建生成镜像。

如果使用 `build` 指令，在 `Dockerfile` 中设置的选项（例如：`CMD`、`EXPOSE`、`VOLUME`、`ENV` 等）将会自动被获取，无需在 Compose 文件中重复设置。

下面分别介绍各个指令的用法。

## 11.5.1 `build`

指定 `Dockerfile` 所在文件夹的路径（可以是绝对路径，或者相对 Compose 文件的路径）。`Compose` 将会利用它自动构建这个镜像，然后使用这个镜像。

```yaml
services:
  webapp:
    build: ./dir
```

你也可以使用 `context` 指令指定 `Dockerfile` 所在文件夹的路径。

使用 `dockerfile` 指令指定 `Dockerfile` 文件名。

使用 `arg` 指令指定构建镜像时的变量。

```yaml
services:
  webapp:
    build:
      context: ./dir
      dockerfile: Dockerfile-alternate
      args:
        buildno: 1
```

使用 `cache_from` 指定构建镜像的缓存

```yaml
build:
  context: .
  cache_from:
    - alpine:latest
    - corp/web_app:3.14
```

## 11.5.2 `cap_add, cap_drop`

指定容器的内核能力 (capability) 分配。

例如，让容器拥有所有能力可以指定为：

```yaml
cap_add:
  - ALL
```

去掉 NET\_ADMIN 能力可以指定为：

```yaml
cap_drop:
  - NET_ADMIN
```

## 11.5.3 `command`

覆盖容器启动后默认执行的命令。

```yaml
command: echo "hello world"
```

## 11.5.4 `configs`

`configs` 来自 Compose Specification。它在 Swarm 中是原生对象；在本地 `docker compose` 模式下通常以文件挂载的形式实现，具体能力取决于 Compose 版本与运行平台。

## 11.5.5 `cgroup_parent`

指定父 `cgroup` 组，意味着将继承该组的资源限制。

例如，创建了一个 cgroup 组名称为 `cgroups_1`。

```yaml
cgroup_parent: cgroups_1
```

## 11.5.6 `container_name`

指定容器名称。默认将会使用 `项目名称_服务名称_序号` 这样的格式。

```yaml
container_name: docker-web-container
```

> 注意：指定容器名称后，该服务将无法进行扩展 (scale)，因为 Docker 不允许多个容器具有相同的名称。

## 11.5.7 `deploy`

`deploy` 用于描述副本数、更新策略、资源限制等部署参数。该字段在 Swarm 中支持最完整；在本地 `docker compose up` 场景下通常只有部分字段生效。

## 11.5.8 `devices`

指定设备映射关系。

```yaml
devices:
  - "/dev/ttyUSB1:/dev/ttyUSB0"
```

## 11.5.9 `depends_on`

解决容器的依赖、启动先后的问题。以下例子中会先启动 `redis` `db` 再启动 `web`

```yaml
services:
  web:
    build: .
    depends_on:
      - db
      - redis

  redis:
    image: redis

  db:
    image: postgres
```

> 注意：上述简写形式中，`web` 服务不会等待 `redis` `db` “完全启动” 之后才启动。

如果需要等待依赖服务就绪，可以使用 `condition` 字段配合 `healthcheck`：

```yaml
services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy

  redis:
    image: redis
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

  db:
    image: postgres
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5
```

`condition` 支持三个值：

* `service_started`：容器启动即满足（默认）。
* `service_healthy`：容器的 `healthcheck` 状态为 healthy 时满足。
* `service_completed_successfully`：容器成功退出（退出码为 0）时满足，适用于初始化任务等一次性容器。

## 11.5.10 `dns`

自定义 `DNS` 服务器。可以是一个值，也可以是一个列表。

```yaml
dns: 8.8.8.8

dns:
  - 8.8.8.8
  - 114.114.114.114
```

## 11.5.11 `dns_search`

配置 `DNS` 搜索域。可以是一个值，也可以是一个列表。

```yaml
dns_search: example.com

dns_search:
  - domain1.example.com
  - domain2.example.com
```

## 11.5.12 `tmpfs`

挂载一个 tmpfs 文件系统到容器。

```yaml
tmpfs: /run
tmpfs:
  - /run
  - /tmp
```

## 11.5.13 `env_file`

从文件中获取环境变量，可以为单独的文件路径或列表。

如果通过 `docker compose -f FILE` 方式来指定 Compose 模板文件，则 `env_file` 中变量的路径会基于模板文件路径。

如果有变量名称与 `environment` 指令冲突，则按照惯例，以后者为准。

```bash
env_file: .env

env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env
```

环境变量文件中每一行必须符合格式，支持 `#` 开头的注释行。

```bash
## common.env: Set development environment

PROG_ENV=development
```

## 11.5.14 `environment`

设置环境变量。你可以使用数组或字典两种格式。

只给定名称的变量会自动获取运行 Compose 主机上对应变量的值，可以用来防止泄露不必要的数据。

```yaml
environment:
  RACK_ENV: development
  SESSION_SECRET:

environment:
  - RACK_ENV=development
  - SESSION_SECRET
```

如果变量名称或者值中用到 `true|false，yes|no` 等表达[布尔](https://yaml.org/type/bool.html)含义的词汇，最好放到引号里，避免 YAML 自动解析某些内容为对应的布尔语义。这些特定词汇，包括

```bash
y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF
```

## 11.5.15 `expose`

暴露端口，但不映射到宿主机，只被连接的服务访问。

仅可以指定内部端口为参数

```yaml
expose:
 - "3000"
 - "8000"
```

## 11.5.16 `external_links`

> 注意：不建议使用该指令。

链接到 Compose 文件外部的容器，甚至并非 `Compose` 管理的外部容器。

```yaml
external_links:
 - redis_1
 - project_db_1:mysql
 - project_db_1:postgresql
```

## 11.5.17 `extra_hosts`

类似 Docker 中的 `--add-host` 参数，指定额外的 host 名称映射信息。

```yaml
extra_hosts:
 - "googledns:8.8.8.8"
 - "dockerhub:52.1.157.61"
```

会在启动后的服务容器中 `/etc/hosts` 文件中添加如下两条条目。

```bash
8.8.8.8 googledns
52.1.157.61 dockerhub
```

## 11.5.18 `healthcheck`

通过命令检查容器是否健康运行。

```yaml
healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"]
  interval: 1m30s
  timeout: 10s
  retries: 3
```

## 11.5.19 `image`

指定为镜像名称或镜像 ID。如果镜像在本地不存在，`Compose` 将会尝试拉取这个镜像。

```yaml
image: ubuntu
image: orchardup/postgresql
image: a4bc65fd
```

## 11.5.20 `labels`

为容器添加 Docker 元数据 (metadata) 信息。例如可以为容器添加辅助说明信息。

```yaml
labels:
  com.startupteam.description: "webapp for a startup team"
  com.startupteam.department: "devops department"
  com.startupteam.release: "rc3 for v1.0"
```

## 11.5.21 `links`

> 注意：不推荐使用该指令。容器之间应通过 Docker 网络 (networks) 进行互联。

## 11.5.22 `logging`

配置日志选项。

```yaml
logging:
  driver: syslog
  options:
    syslog-address: "tcp://192.168.0.42:123"
```

Docker 支持十余种日志驱动（`json-file`、`local`、`syslog`、`journald`、`gelf`、`fluentd`、`awslogs`、`splunk`、`gcplogs`、`none` 等，默认为 `json-file`），完整清单见[官方文档](https://docs.docker.com/engine/logging/configure/)。下面是几个常见取值：

```yaml
driver: "json-file"
driver: "syslog"
driver: "none"
```

`options` 配置日志驱动的相关参数。

```yaml
options:
  max-size: "200k"
  max-file: "10"
```

## 11.5.23 `network_mode`

设置网络模式。使用和 `docker run` 的 `--network` 参数一样的值。

```yaml
network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
```

## 11.5.24 `networks`

配置容器连接的网络。

```yaml
services:

  some-service:
    networks:
     - some-network
     - other-network

networks:
  some-network:
  other-network:
```

## 11.5.25 `pid`

跟主机系统共享进程命名空间。打开该选项的容器之间，以及容器和宿主机系统之间可以通过进程 ID 来相互访问和操作。

```yaml
pid: "host"
```

## 11.5.26 `ports`

暴露端口信息。

使用宿主端口：容器端口 `(HOST:CONTAINER)` 格式，或者仅仅指定容器的端口（宿主将会随机选择端口）都可以。

```yaml
ports:
 - "3000"
 - "8000:8000"
 - "49100:22"
 - "127.0.0.1:8001:8001"
```

*注意：当使用 `HOST:CONTAINER` 格式来映射端口时，如果你使用的容器端口小于 60 并且没放到引号里，可能会得到错误结果，因为 `YAML` 会自动解析 `xx:yy` 这种数字格式为 60 进制。为避免出现这种问题，建议数字串都采用引号包括起来的字符串格式。*

## 11.5.27 `secrets`

存储敏感数据，例如 `mysql` 服务密码。

```yaml
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
    secrets:
      - db_root_password
      - my_other_secret

secrets:
  db_root_password:
    file: ./db_root_password.txt
  my_other_secret:
    external: true
```

## 11.5.28 `security_opt`

指定容器模板标签 (label) 机制的默认属性（用户、角色、类型、级别等）。例如配置标签的用户名和角色名。

```yaml
security_opt:
    - label:user:USER
    - label:role:ROLE
```

## 11.5.29 `stop_signal`

设置另一个信号来停止容器。在默认情况下使用的是 SIGTERM 停止容器。

```yaml
stop_signal: SIGUSR1
```

## 11.5.30 `sysctls`

配置容器内核参数。

```yaml
sysctls:
  net.core.somaxconn: 1024
  net.ipv4.tcp_syncookies: 0

sysctls:
  - net.core.somaxconn=1024
  - net.ipv4.tcp_syncookies=0
```

## 11.5.31 `ulimits`

指定容器的 ulimits 限制值。

例如，指定最大进程数为 65535，指定文件句柄数为 20000（软限制，应用可以随时修改，不能超过硬限制）和 40000（系统硬限制，只能 root 用户提高）。

```yaml
  ulimits:
    nproc: 65535
    nofile:
      soft: 20000
      hard: 40000
```

## 11.5.32 `volumes`

数据卷所挂载路径设置。可以设置为宿主机路径 (`HOST:CONTAINER`) 或者数据卷名称 (`VOLUME:CONTAINER`)，并且可以设置访问模式 (`HOST:CONTAINER:ro`)。

该指令中路径支持相对路径。

```yaml
volumes:
 - /var/lib/mysql
 - cache/:/tmp/cache
 - ~/configs:/etc/configs/:ro
```

如果路径为数据卷名称，必须在文件中配置数据卷。

```yaml
services:
  my_src:
    image: mysql:8.4
    volumes:
      - mysql_data:/var/lib/mysql

volumes:
  mysql_data:
```

## 11.5.33 其他指令

此外，还有包括 `domainname, entrypoint, hostname, ipc, mac_address, privileged, read_only, shm_size, restart, stdin_open, tty, user, working_dir` 等指令，基本跟 `docker run` 中对应参数的功能一致。

指定服务容器启动后执行的入口文件。

```yaml
entrypoint: /code/entrypoint.sh
```

指定容器中运行应用的用户名。

```yaml
user: nginx
```

指定容器中工作目录。

```yaml
working_dir: /code
```

指定容器中搜索域名、主机名、mac 地址等。

```yaml
domainname: your_website.com
hostname: test
mac_address: 08-00-27-00-0C-0A
```

允许容器中运行一些特权命令。`privileged: true` 会显著扩大容器对宿主机设备和 Linux capability 的访问范围，生产环境应优先使用更窄的 `cap_add`、`devices` 或只读挂载；更多说明见 [内核能力机制](/docker_practice/di-si-bu-fen-shi-zhan-pian/18_security/18.4_kernel_capability.md)。

```yaml
privileged: true
```

指定容器退出后的重启策略。该命令对保持服务始终运行十分有效，在生产环境中推荐配置为 `always` 或者 `unless-stopped`。

| 策略                         | 说明                                 |
| -------------------------- | ---------------------------------- |
| `no`                       | 默认值，不自动重启                          |
| `always`                   | 无论退出码如何，始终重启；Docker 守护进程启动时也会重启    |
| `on-failure[:max-retries]` | 仅在非零退出码时重启，可指定最大重试次数               |
| `unless-stopped`           | 类似 `always`，但手动停止的容器在守护进程重启后不会自动启动 |

```yaml
restart: always
```

以只读模式挂载容器的 root 文件系统，意味着不能对容器内容进行修改。

```yaml
read_only: true
```

打开标准输入，可以接受外部输入。

```yaml
stdin_open: true
```

模拟一个伪终端。

```yaml
tty: true
```

## 11.5.34 `profiles`

`profiles` 用于按场景选择性启动服务。未指定 `profiles` 的服务默认始终启动；标记了 `profiles` 的服务仅在激活对应 profile 时才启动。

```yaml
services:
  web:
    image: nginx

  debug:
    image: busybox
    profiles:
      - debug

  test:
    image: node
    profiles:
      - test
```

启动时通过 `--profile` 激活：

```bash
$ docker compose --profile debug up    # 启动 web + debug
$ docker compose up                    # 仅启动 web
```

也可以通过环境变量激活：

```bash
$ COMPOSE_PROFILES=debug,test docker compose up
```

如果在命令行里显式指定某个带 profile 的服务，Compose 会自动启动这个目标服务及其声明的依赖；但不会自动启动同一 profile 下的其他服务，除非也显式指定或通过 `--profile` / `COMPOSE_PROFILES` 启用。

## 11.5.35 读取变量

Compose 模板文件支持动态读取主机的系统环境变量和当前目录下的 `.env` 文件中的变量。

例如，下面的 Compose 文件将从运行它的环境中读取变量 `${MONGO_VERSION}` 的值，并写入执行的指令中。

```yaml
services:
  db:
    image: "mongo:${MONGO_VERSION}"
```

如果执行 `MONGO_VERSION=3.2 docker compose up` 则会启动一个 `mongo:3.2` 镜像的容器；如果执行 `MONGO_VERSION=2.8 docker compose up` 则会启动一个 `mongo:2.8` 镜像的容器。

若当前目录存在 `.env` 文件，执行 `docker compose` 命令时将从该文件中读取变量。

在当前目录新建 `.env` 文件并写入以下内容。

```bash
## 支持 # 号注释

MONGO_VERSION=3.6
```

执行 `docker compose up` 则会启动一个 `mongo:3.6` 镜像的容器。
