Using DotEnv and Docker Compose

None

What do Corn Flakes, Popsicles and Post-It Notes have in common? That’s right, they were created by accident, as a by-product of other forms of experimentation. By chance recently, I found out that we can pass the environment variables to the docker-compose.yml configuration from the .env (aka DotEnv) file located in the same directory.

Why is this important, and how does it work?

Let’s say that there is a database connection string in your project’s configuration:
DB_URL = os.environ.get('DB_URL')

So, it is taken from an environment variable DB_URL. If we use Docker for work (and we do, because we are pros, ha), then we know that environment variables can be set in the docker-compose.yml file.

It looks something like this:
services:
    app:
        environment:
            DB_URL: and here is the connection string

However, if there are a lot of people in the team and someone wanted to play with the DB, then it can be a bit inconvenient as synchronization problems such as Git conflicts and misunderstandings can occur. 
In this case, it is comfortable to initialize environment variables from a .env (DotEnv) file, solely yours and not in the git. 
Just create a new .env file in the same folder as docker-compose.yml and enter:

DB_URL=postgres://postgres:example@db:5432/190827
Then, in docker-compose.yml you write this:
services:

    app:
        environment:
            DB_URL: ${DB_URL}

It’s that simple, smart Docker will subsequently pull everything up out of the box. 
To view the compiled configuration use the command `docker-compose config` which prints your resolved application configuration to the terminal:

$ docker-compose config
services:
    app:
        environment:
            DB_URL: postgres://postgres:example@db:5432/190827

If you’re using Docker Compose, tips like this can save you time and money. At Edicasoft, our knowledgeable and motivated team can help you to give your project a boost, or provide much needed direction if you’re unsure of which step to take. For any queries don’t hesitate to get in touch!