包含

要求: Docker Compose 2.20.3 及更高版本

透過 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 file

my-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 模型。

參考資訊

include 頂層元素