After reading the config point of the 12 factor app I decided to override my config file containing default value with environment variable.
I have 3 Dockerfile
s, one for an API, one for a front-end and one for a worker. I have one docker-compose.yml
to run those 3 services plus a database.
Now I'm wondering if I should define the environment variables in Dockerfile
s or docker-compose.yml
? What's the difference between using one rather than another ?
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. yml.
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.
But docker-compose does not stop at the . env and the host's current environment variables. It's cool that you can simply override values of your . env file, but this flexibility is can also be the source of nasty bugs.
The key difference between the Dockerfile and docker-compose is that the Dockerfile describes how to build Docker images, while docker-compose is used to run Docker containers.
See this:
You can set environment variables in a service’s containers with the 'environment' key, just like with docker run -e VARIABLE=VALUE ...
Also, you can use ENV in dockerfile to define a environment variable.
The difference is:
Environment variable define in Dockerfile
will not only used in docker build
, it will also persist into container. This means if you did not set -e
when docker run
, it will still have environment variable same as defined in Dockerfile
.
While environment variable define in docker-compose.yaml
just used for docker run
.
Maybe next example could make you understand more clear:
Dockerfile:
FROM alpine
ENV http_proxy http://123
docker-compose.yaml:
app:
environment:
- http_proxy=http://123
If you define environment variable in Dockerfile
, all containers used this image will also has the http_proxy
as http://123
. But the real situation maybe when you build the image, you need this proxy. But, the container maybe run by other people maybe not need this proxy or just have another http_proxy, so they had to remove the http_proxy
in entrypoint or just change to another value in docker-compose.yaml
.
If you define environment variable in docker-compose.yaml
, then user could just choose his own http_proxy when do docker-compose up
, http_proxy
will not be set if user did not configure it docker-compose.yaml
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With