Use docker-compose env variable in Dockerbuild file

后端 未结 3 604
粉色の甜心
粉色の甜心 2020-12-24 12:40

Having the following docker-compose file:

db:
    build: .
    environment:
        - MYSQL_ROOT_PASSWORD=password
        - ENV=test
    env_file: .env


        
相关标签:
3条回答
  • 2020-12-24 13:16

    Although this question was asked long ago, there is an answer to a similar question here: Pass environment variables from docker-compose to container at build stage

    Basically, to use variables at the container's build time one has to define the variable in docker-compose.yml:

    build:
      context: .
      args:
        MYSQL_ROOT_PASSWORD: password
        ENV: test
    

    and then reference it in the Dockerfile using ARG:

    ARG MYSQL_ROOT_PASSWORD
    ARG ENV
    ADD ${ENV}/data.xml /data/
    

    Concerning environment variables defined in an *.env file, I believe that they can't be passed to the container at build time.

    0 讨论(0)
  • 2020-12-24 13:19

    This approach goes against the 'build once, run anywhere' theory behind Docker and most DevOps approaches. With this approach you'll need to build a container for every environment you expect to use. By doing so you can't safely say if a container works in the dev environment it will work in staging and production since you aren't using the same container.

    You'd be better off adding all config files you need on to the container and writing an entrypoint script that selects/copies the data for that environment to the correct location when the container starts. You can also apply this approach to other config on the container, like templated Apache config using jinja2 templates etc.

    0 讨论(0)
  • 2020-12-24 13:26

    It works ok this way:

    docker-compose.yml

    version: '3.5'
    
    services:
        container:
            build:
                context: .
                args:
                    ENV: ${ENV} # from .env file
            env_file:
                - .env
    

    Dockerfile

    # from compose args
    ARG ENV 
    ADD ${ENV}/data.xml /data/
    

    .env

    ENV=myenv
    

    Thus all the values are taken from .env file

    0 讨论(0)
提交回复
热议问题