配置文件

通过配置文件,您可以定义一组活动配置文件,以便针对各种用途和环境调整您的Compose应用程序模型。

The services top-level element supports a profiles attribute to define a list of named profiles. Services without a profiles attribute are always enabled.

当列出的 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,则模型包含 webdebug_lib 服务,但不包含 test_libcoverage_lib, 因此该模型关于 debug_libdepends_on 约束是无效的。
  • 如果配置文件 debugtest 被启用,则该模型包含所有服务;webtest_libcoverage_libdebug_lib
  • 如果 Compose 以 test_lib 作为显式服务运行,即使未启用 test 配置文件,test_libtest 配置文件也会处于活动状态。
  • 如果 Compose 以 coverage_lib 作为要运行的显式服务执行,则服务 coverage_lib 和配置文件 test 处于活动状态,并且 test_libdepends_on 约束引入。
  • 如果 Compose 以 debug_lib 作为要运行的显式服务执行,则该模型关于 debug_libdepends_on 约束再次无效,因为 debug_libtest_lib 没有列出共同的 profiles
  • 如果 Compose 在执行时将 debug_lib 作为显式服务运行,并且启用了配置文件 test,则会自动启用配置文件 debug,并引入服务 test_lib 作为依赖项,从而同时启动服务 debug_lib 和服务 test_lib

了解如何在 Docker Compose 中使用 profiles