Search code examples
dockerdocker-compose

How can I use environment variables in docker-compose?


I would like to be able to use environment variables inside docker-compose.yml, with values passed in at the time of docker-compose up. This is the example.

I am doing this today with a basic docker run command, which is wrapped around my own script. Is there a way to achieve it with compose, without any such bash wrappers?

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

Solution

    1. Create a template.yml, which is your docker-compose.yml with environment variable.
    2. Suppose your environment variables are in a file 'env.sh'
    3. Put the below piece of code in a sh file and run it.
    source env.sh
    rm -f docker-compose.yml
    envsubst < "template.yml" > "docker-compose.yml"
    

    A new file docker-compose.yml will be generated with the correct values of environment variables.

    Sample template.yml file:

    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}
    

    Sample env.sh file:

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