Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use docker-compose env variable in Dockerbuild file

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"] 
like image 531
ecyshor Avatar asked Mar 25 '15 16:03

ecyshor


People also ask

Can I use environment variables in Docker compose file?

It seems that docker-compose has native support now for default environment variables in file. all you need to do is declare your variables in a file named . env and they will be available in docker-compose.

How do I pass an environment variable from Docker Compose to Dockerfile?

Pass variables into Dockerfile through Docker Compose during build. If you want to pass variables through the docker-compose process into any of the Dockerfiles present within docker-compose. yml , use the --build-arg parameter for each argument to flow into all of the Dockerfiles.

Can I use variables in .env file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.


1 Answers

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.

like image 154
BartoNaz Avatar answered Sep 18 '22 14:09

BartoNaz