Search code examples
dockerdocker-composeenvironment-variablesdockerfile12factor

Define environment variable in Dockerfile or docker-compose?


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 ?


Solution

  • 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.