Search code examples
docker

How do I use environment variables in .env file in docker-compose.yml?


I am trying to use an environment variable in the docker-compose.yml file. I have a file my-great-env.env.

Here is how they look:

docker-compose.yml

version: '3.4'

services:
    blahblah:
        images: greatimage
        volumes:
          - "${MY_PATH}:c:\\FinalFolder"

my-great-env.env

MY_PATH=C:\the\path\to\folder

When I try to docker run this, I get

The MY_PATH variable is not set. Defaulting to a blank string.

How do I use the environment variables defined in the .env file in docker-compose.yml?


Solution

  • There are two aspects of your problem:

    1. if you want to use the environment vars in docker-compose.yml file, you have to put them in file named .env as stated here: https://docs.docker.com/compose/environment-variables/#the-env-file
    2. you can use the env_file configuration option to use any file with variables definitions as described here: https://docs.docker.com/compose/environment-variables/set-environment-variables/#use-the-env_file-attribute BUT! they will be visible only in containers, not in the docker-compose.yml file.