When working with Docker, it can be a bit of a chore to have to pass your environment variables in from the command line. Fortunately Docker has built in support for environment variables coming from a .env file. As such, it is really easy to set your docker-compose.yml file up to make use of environment variables.
Unlike when working with .env files in Node.js or Python, you do not need to install anything or do any setup. Let's say you wanted to pass your bcrypt secret key and your Auth0 client secret into your app via environment variables - you could do this in your .env
file:
SECRET_KEY=A98evJHg19as7kFMxzXoq9ByEnpnmdBTKIdBZTXPgzvYQtpvzy
AUTH0_SECRET=lKtgyz0z6wceZ7kJYZjNeRY05dzlhNCqzItHIBbjj2HY7aFs136m5ptDm7wa30Rt
Then, in your docker-compose.yml
file, you would specify the environment variables in the format:
VARIABLE_NAME=${ENV_FILE_VARIABLE_NAME}
As such, you could do something like this (Note the "environment" section):
...
services:
api:
build:
context: ./services/users
dockerfile: Dockerfile
entrypoint: ["/usr/src/app/entrypoint.sh"]
volumes:
- ./services/api:/usr/src/app
ports:
- 5001:5000
environment:
- FLASK_ENV=development
- APP_SETTINGS=project.config.DevelopmentConfig
- SECRET_KEY=${SECRET_KEY}
- AUTH0_SECRET=${AUTH0_SECRET}
depends_on:
- db
...
Simples!
While we are on the topic of docker-compose. A very useful tip is to assign an alias in your .bashrc
file as follows:
alias dc='docker-compose'
Once saved, run: source ~/.bashrc
This then enables you to us dc
in the command line instead of typing out the entire docker-compose
command! Very useful!
Hat Tip to Michael Herman and his incredible Testdriven.io courses!