Use docker-compose env variable in Dockerbuild file

DockerDocker Compose

Docker Problem Overview


Having the following docker-compose file:

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

Is there any way to use the env variables declared in docker-compose.yml (either as environment or declared in the env_file) as part of Dockerfile without declaring them in the Dockerfile? Something like this:

FROM java:7
ADD ${ENV}/data.xml /data/
CMD ["run.sh"]

Docker Solutions


Solution 1 - Docker

Although this question was asked long ago, there is an answer to a similar question here: https://stackoverflow.com/questions/41747843/pass-environment-variables-from-docker-compose-to-container-at-build-stage/41792420#41792420

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.

Solution 2 - Docker

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

Solution 3 - Docker

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionecyshorView Question on Stackoverflow
Solution 1 - DockerBartoNazView Answer on Stackoverflow
Solution 2 - DockerDaniel TitkovView Answer on Stackoverflow
Solution 3 - Dockerandyberry88View Answer on Stackoverflow