擴充套件你的 Compose 檔案
Docker Compose 的 extends
屬性 允許你在不同的檔案甚至完全不同的專案之間共享通用配置。
如果你有多個服務重用一組通用配置選項,擴充套件服務會很有用。使用 extends
,你可以在一個地方定義一組通用服務選項,並從任何地方引用它。你可以引用另一個 Compose 檔案並選擇你想要在自己的應用程式中使用的服務,並能夠根據自己的需求覆蓋某些屬性。
重要當你使用多個 Compose 檔案時,你必須確保檔案中的所有路徑都是相對於基本 Compose 檔案(即主專案資料夾中的 Compose 檔案)的。這是因為擴充套件檔案不必是有效的 Compose 檔案。擴充套件檔案可以包含小的配置片段。跟蹤服務的哪個片段相對於哪個路徑是困難且令人困惑的,因此為了使路徑更容易理解,所有路徑都必須相對於基本檔案定義。
extends
屬性的工作原理
從另一個檔案擴充套件服務
請看以下示例
services:
web:
extends:
file: common-services.yml
service: webapp
這指示 Compose 只重用 common-services.yml
檔案中定義的 webapp
服務的屬性。webapp
服務本身不屬於最終專案。
如果 common-services.yml
看起來像這樣
services:
webapp:
build: .
ports:
- "8000:8000"
volumes:
- "/data"
你將獲得與直接在 web
下定義相同的 build
、ports
和 volumes
配置值寫入 compose.yaml
完全相同的結果。
要從另一個檔案擴充套件服務時將服務 webapp
包含在最終專案中,你需要在當前的 Compose 檔案中顯式包含這兩個服務。例如(這僅用於說明目的)
services:
web:
build: alpine
command: echo
extends:
file: common-services.yml
service: webapp
webapp:
extends:
file: common-services.yml
service: webapp
或者,你可以使用 include。
在同一檔案內擴充套件服務
如果你在同一個 Compose 檔案中定義服務並從另一個服務擴充套件一個服務,則原始服務和擴充套件服務都將成為你最終配置的一部分。例如
services:
web:
build: alpine
extends: webapp
webapp:
environment:
- DEBUG=1
在同一檔案內和從另一個檔案擴充套件服務
你可以進一步在 compose.yaml
中本地定義或重新定義配置
services:
web:
extends:
file: common-services.yml
service: webapp
environment:
- DEBUG=1
cpu_shares: 5
important_web:
extends: web
cpu_shares: 10
附加示例
當你擁有具有通用配置的多個服務時,擴充套件單個服務很有用。以下示例是一個包含兩個服務的 Compose 應用程式,一個 Web 應用程式和一個佇列工作器。這兩個服務使用相同的程式碼庫並共享許多配置選項。
common.yaml
檔案定義了通用配置
services:
app:
build: .
environment:
CONFIG_FILE_PATH: /code/config
API_KEY: xxxyyy
cpu_shares: 5
compose.yaml
定義了使用通用配置的具體服務
services:
webapp:
extends:
file: common.yaml
service: app
command: /code/run_web_app
ports:
- 8080:8080
depends_on:
- queue
- db
queue_worker:
extends:
file: common.yaml
service: app
command: /code/run_worker
depends_on:
- queue
相對路徑
當使用帶有指向另一個資料夾的 file
屬性的 extends
時,被擴充套件服務宣告的相對路徑會被轉換,以便它們在被擴充套件服務使用時仍指向同一個檔案。這在以下示例中進行說明
基本 Compose 檔案
services:
webapp:
image: example
extends:
file: ../commons/compose.yaml
service: base
commons/compose.yaml
檔案
services:
base:
env_file: ./container.env
生成的服務引用 commons
目錄中的原始 container.env
檔案。這可以透過 docker compose config
進行確認,它會檢查實際模型
services:
webapp:
image: example
env_file:
- ../commons/container.env