Docker Community Forums

Share and learn in the Docker community.

Concatenate two environment variable in docker-compose

Hi,

I am trying to use environment variable under volumes in docker-compose.

My .env file contains below

master_1=hadoop-master1
master_2=hadoop-master2
docker_storage=/storage/volumes/data/
master_1_storage={docker_storage} {master_1}
master_2_storage={docker_storage}{master_2}

My docker compose file volumes section.

   privileged: true
   volumes:
      - "${cgroup_vol}:${cgroup_vol}:ro"
      - "${master_1_storage}:/data/"
      - "${master_1_hdfs:${hadoop_data}"
   environment:

I am receiving below error for docker-compose config command. Please support how to concatenate tow environment variable in docker-compose file.

ERROR: Named volume “”{docker_storage} {master_1}":/data:rw" is used in service “master_1” but no declaration was found in the volumes section

You can’t use variables in the .env file. From the .env file docs: “Compose expects each line in an env file to be in VAR=VAL format.”

ok, Is there any way to concatenate two variable in docker-compose ?

Regards,
Sakthi

Just write one after the other. ${docker_storage}${master_1}

You can manually source the .env file and then have the variables available for docker-compose.
Example:

set -o allexport;
source .env;
docker-compose up -d;
set +o allexport;

set -o is a bash flag to allow exported variables to be available to the following commands. set +o resets the flag.
I personally prefer this option rather than duplicating strings in .env files

Please note also that the .env file should reflect bash syntax, therefore, your .env should become:

docker_storage=/storage/volumes/data/
master_1_storage="${docker_storage}${master_1}"

Note the $,{,}, around the variable to be replaced. And also, it allows quotes.
And the same thing applies in your yaml file:

"${master_1_hdfs}:${hadoop_data}"