Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in DevOps and Agile by (2.3k points)

Hey there, Is there any way I can use environment variables inside of my docker-compose.yml file? The values for these env variables will be passed at the time of using the command docker-compose up

In my example below I am making use of a basic docker run command that is wrapped by my own created script.

Can anyone tell me a way to do this within compose and without the use of wrappers?

proxy:
  hostname: $hostname
  volumes:
    - /mnt/data/logs/$hostname:/logs
    - /mnt/data/$hostname:/data

1 Answer

0 votes
by (6.9k points)

Follow these steps, it shouldn't go wrong : 

  1. First go ahead and create a file called template.yml, this file is basically going to be yourdocker-compose.yml, with you environment variables.
  2. Now create a file called 'env.sh' , your environment variables are going to be in this.
  3. Now run the below code in a .sh file.

source env.sh; rm -rf docker-compose.yml; envsubst < "template.yml" > "docker-compose.yml";

This will create a new docker-compose.yml file with all the right values of environment.

Here is a sample template.yml file given below:

oracledb:
        image: ${ORACLE_DB_IMAGE}
        privileged: true
        cpuset: "0"
        ports:
                - "${ORACLE_DB_PORT}:${ORACLE_DB_PORT}"
        command: /bin/sh -c "chmod 777 /tmp/start; /tmp/start"
        container_name: ${ORACLE_DB_CONTAINER_NAME}

Here is a sample 'env.sh' file given below:

#!/bin/bash 
export ORACLE_DB_IMAGE=<image-name> 
export ORACLE_DB_PORT=<port to be exposed> 
export ORACLE_DB_CONTAINER_NAME=ORACLE_DB_SERVER

Hope this helps :)


Want to get better in docker and it's related topics ? Try out docker training course. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...