一尘不染

在docker-compose yml中重用环境变量

docker

是否可以重用在多个容器之间共享的环境变量以避免重复,如本示例所示:

version: '2'

services:

  db:
    image: example/db
    ports:
      - "8443:8443" 
    container_name: db
    hostname: db
    environment:
      - USER_NAME = admin 
      - USER_PASSWORD = admin

svc:
  image: example/svc
  depends_on:
    - db
  ports:
    - "9443:9443"
  container_name: svc
  hostname: svc
  environment:
    - DB_URL = https://db:8443
    - DB_USER_NAME = admin
    - DB_USER_PASSWORD = admin

阅读 573

收藏
2020-06-17

共1个答案

一尘不染

extends选项可能是好的,但它不支持3.x撰写文件。其他走的方式是:

  1. 扩展名字(撰写文件3.4+)

如果可以使用3.4+组成文件,则扩展名字段可能是最佳选择:

docker-compose.yml

    version: '3.4'

x-common-variables: &common-variables
  VARIABLE: some_value
  ANOTHER_VARIABLE: another_value

services:
  some_service:
    image: someimage
    environment: *common-variables

  another_service:
    image: anotherimage
    environment:
      <<: *common-variables
      NON_COMMON_VARIABLE: 'non_common_value'
  1. env_file指令

docker-compose.yml

    version: '3.2'

services:
  some_service:
    image: someimage
    env_file:
      - 'variables.env'

  another_service:
    image: anotherimage
    env_file:
      - 'variables.env'

variables.env

    VARIABLE=some_value
ANOTHER_VARIABLE=another_value
  1. * 项目根目录中的 *.env 文件(或实际撰写环境中的变量)

.env文件中的变量可以在服务配置中引用:

docker-compose.yml

    version: '3.2'

services:
  some_service:
    image: someimage
    environment:
      - VARIABLE

  another_service:
    image: anotherimage
    environment:
      - VARIABLE
      - ANOTHER_VARIABLE

.env

    VARIABLE=some_value
ANOTHER_VARIABLE=another_value
2020-06-17