Define environment variable in Dockerfile or docker-compose?
Asked Answered
P

1

14

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 Dockerfiles, 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 Dockerfiles or docker-compose.yml ? What's the difference between using one rather than another ?

Poseur answered 12/8, 2019 at 0:37 Comment(0)
B
23

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.

Byrle answered 12/8, 2019 at 2:23 Comment(3)
Thanks so I can define it in Dockerfile and if needed it can be overrided in docker-compose.yml if I understood correctlyPoseur
Yes, define in Dockerfile will not only affect docker build but also docker run, define in docker-compose could override docker run.Byrle
michael your 2 line long sentence should be the correct answerVarney

© 2022 - 2024 — McMap. All rights reserved.