包含

在 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 頂級元素