包含

在 Docker Compose 版本 2.20.3 中引入
使用 include,您可以将一个单独的 compose.yaml 文件直接合并到当前的 compose.yaml 文件中。这使得将复杂的应用程序模块化为子 Compose 文件变得轻而易举,进而可以简化和明确应用程序配置。

include 顶级元素有助于在配置文件的组织中直接反映负责代码的工程团队。它还解决了 extendsmerge 存在的相对路径问题。

include 部分中列出的每个路径都将作为一个独立的 Compose 应用程序模型加载,并有自己的项目目录,以解析相对路径。

加载包含的 Compose 应用程序后,所有资源都将复制到当前的 Compose 应用程序模型中。

注意

include 递归应用,因此包含的 Compose 文件声明了自己的 include 部分,会导致那些其他文件也被包含在内。

示例

include:
  - my-compose-include.yaml  #with serviceB declared
services:
  serviceA:
    build: .
    depends_on:
      - serviceB #use serviceB directly as if it was declared in this Compose file

my-compose-include.yaml 管理 serviceB,它详细说明了一些副本、用于检查数据的 Web UI、隔离的网络、用于数据持久化的卷等。依赖 serviceB 的应用程序不需要了解基础设施细节,并且将 Compose 文件用作它可以依赖的构建块。

这意味着管理 serviceB 的团队可以重构其自己的数据库组件以引入其他服务,而不会影响任何依赖团队。这也意味着依赖团队不需要在其运行的每个 Compose 命令中包含额外的标志。

包含和覆盖

如果 include 中的任何资源与包含的 Compose 文件中的资源发生冲突,Compose 会报告错误。此规则可防止与包含的 Compose 文件作者定义的资源发生意外冲突。但是,在某些情况下,您可能需要调整包含的模型。这可以通过向 include 指令添加一个覆盖文件来实现

include:
  - path : 
      - third-party/compose.yaml
      - override.yaml  # local override for third-party model

这种方法的主要限制是您需要为每个包含维护一个专用覆盖文件。对于包含多个包含的复杂项目,这会导致生成许多 Compose 文件。

另一个选择是使用 compose.override.yaml 文件。虽然使用 include 时会拒绝来自相同资源声明的文件的冲突,但全局 Compose 覆盖文件可以覆盖生成的合并模型,如下例所示

compose.yaml 文件

include:
  - team-1/compose.yaml # declare service-1
  - team-2/compose.yaml # declare service-2

覆盖 compose.override.yaml 文件

services:
  service-1:
    # override included service-1 to enable debugger port
    ports:
      - 2345:2345

  service-2:
    # override included service-2 to use local data folder containing test data
    volumes:
      - ./data:/data

组合在一起,这使您可以从第三方可重复使用的组件中受益,并根据您的需要调整 Compose 模型。

参考信息

include 顶级元素