DEV Community

Mohamad Ashraful Islam
Mohamad Ashraful Islam

Posted on

Did you know docker-compose only takes environment variables from`.env` only?

Recently I have encountered an issue with docker compose. I have separated the environment files and declared todocker-compose.yaml like following,

    env_file:
      - .dev_env
Enter fullscreen mode Exit fullscreen mode

When I ran docker compose up, it was not working on the compose itself but the container. because of environment variables. Then I found following solution for this.

docker compose --env-file .dev_env --env-file .prod_env up
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
ratulsharker profile image
Ratul sharker

We have been using this in docker 24.0.2

web:
  env_file:
    - web-variables.env
Enter fullscreen mode Exit fullscreen mode

Even it can process multiple files, where one key declared in one file can be overridden by the declaration of the same key in later file(s)

env_file:
  - ./a.env
  - ./b.env
Enter fullscreen mode Exit fullscreen mode

Moreover docker prioritise taking value from the host environment first. If it's not declared then, it's tried to resolved from the .env file or the file provided specified.

After all fail attempt to retrieve the value it uses the default value given after the :- in the docker-compose.yml file.

# sample docker file

services:
  sample-service:
    environment:
      KEY: ${ENV_KEY:-YOUR_DEFAULT_VALUE}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ashraful profile image
Mohamad Ashraful Islam

Thank you for your point. But in my case I was using the env variables on the compose file itself. like following,

ports:
  - 9000:${CUSTOM_PORT}
Enter fullscreen mode Exit fullscreen mode