Re-using environment variables in docker-compose.yml

后端 未结 3 2106
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 16:45

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:



        
3条回答
  •  孤街浪徒
    2020-12-07 17:08

    You can use the extends directive (available in compose 1.x and 2.x) to have multiple containers inherit the environment configuration from an underlying service description. For example, put the following in a file named base.yml:

    version: '2'
    
    services:
      base:
        environment:
          DB_URL: https://db:8443
          DB_USER_NAME: admin
          DB_USER_PASSWORD: admin 
    

    Then in your docker-compose.yml:

    version: '2'
    
    services:
      container1:
        image: alpine
        command: sh -c "env; sleep 900"
        extends:
          file: base.yml
          service: base
    
      container2:
        image: alpine
        command: sh -c "env; sleep 900"
        extends:
          file: base.yml
          service: base
        environment:
          ANOTHERVAR: this is a test
    

    Then inside of container1, you will see:

    DB_URL=https://db:8443
    DB_USER_NAME=admin
    DB_USER_PASSWORD=admin
    

    And inside of container2 you will see:

    DB_URL=https://db:8443
    DB_USER_NAME=admin
    DB_USER_PASSWORD=admin
    ANOTHERVAR=this is a test
    

    You can obviously use extends for things other than the environment directive; it's a great way to avoid duplication when using docker-compose.

提交回复
热议问题