Use docker-compose env variable in Dockerbuild file

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.

Leave a Comment