Using environment variables in your code with docker-compose.yml

In this blog, you will learn to access environment variables in your code with docker-compose.yml. This blog assumes that you are using python


To start off, if you are curious about how you can use environment variables in your code from docker-compose file, basically it takes variable assigned to variables under the "environment" section in the docker-compose file. A picture below will demonstrate how it works.


1 - Docker Compose where you initialize the environment variable
2 - The code where you use the environment variable
3 - The output


Method 1: Using .env

This is probably one of the most common method because it is easy to use. However, if you use this method, you will need to remember to add this file into .gitignore if you are storing private credentials.

1) To start with, create your .env file and insert your environment variables like so:

KEY=VALUE

2) Next, add this line of code below the service that would be using the environment variables in your .env file.

 env_file: .env

Note: You can name your .env file and it should work just fine. Example: credentials.env

3) Do "docker compose build"

4) Do "docker compose up" and you are done. 


Method 2: Passing the variables through the command line

You can pass environment variables to your docker-compose file with these 3 commands:


1) docker-compose --env-file <env-file> up
2) docker-compose run -e <env-var>=<value> <service-name>
3) docker-compose build --build-args <build-arg>


Prerequisites for (1):

Assign the environment variable in your .env file to the to any variable under the "environment" section of docker-compose.yml as shown below:



The variable on the left is the one to be used in your code
The variable on the right is taken from your .env file

Prerequisites for (2):

Same as (1)


Prerequisites for (3):

For this method, you will be using dockerfile to use the passed build arguments. Basically, you will type in the docker-compose build --build-args <build-arg> and the build arguments will be captured by dockerfile. Here are the steps:

1) Run the command with the build arguments you want to pass.

2) Add this line of code to your dockerfile

ARG buildvar

ENV envvar=$buildvar

3) Use your environment variable by running "os.envrion.get('envvar')"

Comments

Popular posts from this blog

Support for the experimental syntax 'decorators' isn't currently enabled (5:3):

How to add environment variables into Heroku container

Running CQL scripts in Cassandra