包含
通过 include,您可以将单独的 compose.yaml 文件直接合并到当前的 compose.yaml 文件中。这使得将复杂的应用程序模块化为子 Compose 文件变得容易,从而使应用程序配置更简单、更明确。
include 顶层元素有助于将负责代码的工程团队直接反映在配置文件组织中。它还解决了 extends 和 合并 所存在的相对路径问题。
include 部分中列出的每个路径都作为单独的 Compose 应用程序模型加载,具有其自己的项目目录,以便解析相对路径。
一旦包含的 Compose 应用程序加载,所有资源都将复制到当前 Compose 应用程序模型中。
注意
include递归应用,因此声明自己include部分的包含 Compose 文件也会导致这些文件被包含。
示例
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 filemy-compose-include.yaml 管理 serviceB,其中详细说明了一些副本、用于检查数据的 Web UI、隔离网络、用于数据持久化的卷等。依赖于 serviceB 的应用程序不需要了解基础设施细节,并将 Compose 文件作为它可以依赖的构建块来使用。
这意味着管理 serviceB 的团队可以重构其自己的数据库组件以引入额外的服务,而不会影响任何依赖团队。这也意味着依赖团队无需在他们运行的每个 Compose 命令中包含额外的标志。
include:
- oci://docker.io/username/my-compose-app:latest # use a Compose file stored as an OCI artifact
services:
serviceA:
build: .
depends_on:
- serviceB include 允许您引用远程源(例如 OCI 工件或 Git 存储库)中的 Compose 文件。
这里 serviceB 在存储在 Docker Hub 上的 Compose 文件中定义。
将覆盖与包含的 Compose 文件一起使用
如果 include 中的任何资源与包含的 Compose 文件中的资源冲突,Compose 会报告错误。此规则可防止与包含的 Compose 文件作者定义的资源发生意外冲突。但是,在某些情况下,您可能希望自定义包含的模型。这可以通过向 include 指令添加覆盖文件来实现
include:
- path :
- third-party/compose.yaml
- override.yaml # local override for third-party model这种方法的主要限制是您需要为每个 include 维护一个专用的覆盖文件。对于具有多个 include 的复杂项目,这将导致许多 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 模型。