配置檔案

目錄

使用配置檔案,您可以定義一組活動配置檔案,以便您的 Compose 應用程式模型根據不同的用法和環境進行調整。

服務 頂層元素支援 profiles 屬性,用於定義命名的配置檔案列表。沒有 profiles 屬性的服務始終處於啟用狀態。

如果列出的 profiles 中沒有一個與活動配置檔案匹配,Compose 將忽略服務,除非服務由命令明確指定為目標。在這種情況下,服務的配置檔案將新增到活動配置檔案集中。

注意

所有其他頂層元素不受 profiles 影響,始終處於活動狀態。

對其他服務的引用(透過 linksextends 或共享資源語法 service:xxx)不會自動啟用原本會被活動配置檔案忽略的元件。相反,Compose 會返回錯誤。

示例

services:
  web:
    image: web_image

  test_lib:
    image: test_lib_image
    profiles:
      - test

  coverage_lib:
    image: coverage_lib_image
    depends_on:
      - test_lib
    profiles:
      - test

  debug_lib:
    image: debug_lib_image
    depends_on:
      - test_lib
    profiles:
      - debug

在上例中

  • 如果解析 Compose 應用程式模型時沒有啟用配置檔案,它只包含 web 服務。
  • 如果啟用了配置檔案 test,模型將包含服務 test_libcoverage_lib,以及始終啟用的服務 web
  • 如果啟用 `debug` 配置檔案,模型將包含 `web` 和 `debug_lib` 服務,但不包含 `test_lib` 和 `coverage_lib` 服務,因此模型在 `debug_lib` 的 `depends_on` 約束方面無效。
  • 如果啟用 `debug` 和 `test` 配置檔案,模型將包含所有服務:`web`、`test_lib`、`coverage_lib` 和 `debug_lib`。
  • 如果使用 `test_lib` 作為顯式執行的服務執行 Compose,即使未啟用 `test` 配置檔案,`test_lib` 和 `test` 配置檔案也將處於活動狀態。
  • 如果使用 `coverage_lib` 作為顯式執行的服務執行 Compose,服務 `coverage_lib` 和配置檔案 `test` 將處於活動狀態,`test_lib` 將由 `depends_on` 約束拉入。
  • 如果使用 `debug_lib` 作為顯式執行的服務執行 Compose,由於 `debug_lib` 和 `test_lib` 沒有共同列出的配置檔案,因此模型在 `debug_lib` 的 `depends_on` 約束方面再次無效。
  • 如果使用 `debug_lib` 作為顯式執行的服務執行 Compose,並且啟用了 `test` 配置檔案,則會自動啟用 `debug` 配置檔案,並將服務 `test_lib` 拉入作為依賴項,從而啟動 `debug_lib` 和 `test_lib` 服務。

檢視如何在 Docker Compose 中使用配置檔案。