包含
使用 include,您可以將單獨的 compose.yaml 檔案直接合併到您目前的 compose.yaml 檔案中。這使得將複雜的應用程式模組化為子 Compose 檔案變得容易,進而使應用程式設定更簡單且更明確。
include 頂層元素有助於在設定檔的組織中直接反映負責該程式碼的工程團隊。它還解決了 extends 和 merge 所帶來的相對路徑問題。
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 filemy-compose-include.yaml 管理 serviceB,其中詳細說明了副本數、用於檢查資料的網頁 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 允許您引用來自遠端來源的 Compose 檔案,例如 OCI 構件或 Git 儲存庫。
在此範例中,serviceB 定義在儲存於 Docker Hub 的 Compose 檔案中。
搭配 Include 使用 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 模型。