Using Environment Variables with Docker Compose

Nov 25, 2019 min read

Docker Compose is a powerful tool for orchestrating your Docker environment. Managing environment information can be easier to do if you setup your Docker configuration in the following way.

Create a docker-compose.yml file

version: '3'
services:
  api:
    environment:
      - DB_USER=${DB_USER_NAME}
      - DB_PASS=${DB_PASSWORD}
      ...

Then in an .env file, in the same directory, you can define your environment specific values.

DO NOT CHECK THIS FILE INTO VERSION CONTROL!!!!

DB_USER_NAME=mydbuser
DB_PASSWORD=mysecretdbpassword
...

With the .env file in the same directory as your docker-compose.yml file, Docker Compose will substitute the values in your environment variables with the corresponding values in the .env file that specific for each environment. This allows your docker-compose.yml file to remain consistent without the possibility of potentially exposing sensitive information through your docker-compose.yml file.

NOTE: It is recommended that you use a secrets management solution like Hashicorp’s Vault to manage sensitive information like credentials.