Re-using environment variables in docker-compose.yml

Sergei Rodionov picture Sergei Rodionov · Mar 29, 2016 · Viewed 26.4k times · Source

Is it possible to re-use environment variables that are shared among multiple containers?

The idea is to avoid duplication, as illustrated in this example:

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 

Answer

Wolphin picture Wolphin · Feb 6, 2018

The extends option can be nice but it's not supported in 3.x compose files. Other ways to go are:

  1. Extension fields (compose file 3.4+)

    If you can use 3.4+ compose files, extension fields are probably the best option:

    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'
    
  2. env_file directive

    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
    
  3. .env file in project root (or variables at actual compose environment)

    Variables from .env file can be referenced in service configuration:

    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