Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of env variable in docker compose run command

Running the command docker-compose run -e TYPE=result mongo_db_backup should give me the value of the given TYPE variable:

mongo_db_backup:
  image: 'mongo:3.4'
  volumes:
    - '/backup:/backup'
  command: sh -c '$$(echo $TYPE)'

But instead I get the error The TYPE variable is not set. Defaulting to a blank string. What am I doing wrong

like image 234
user3142695 Avatar asked Nov 21 '25 09:11

user3142695


1 Answers

It happens that Compose expands $TYPE before it gets to the inside of the container. Compose looks for the $TYPE environment variable in the shell or host environment and substitutes its value in.

This will work with the following terminal command:

docker-compose.yml

command: sh -c 'echo $TYPE'

terminal command

TYPE='hello world' docker-compose run web

When there is no $TYPE environment variable in the host machine, Compose sets the value of $TYPE to an empty string and outputs a warning.

Compose needs to be informed not to expand $TYPE since we want it expanded inside of the shell running in the container.

For this use

docker-compose.yml

command: sh -c "echo $$TYPE"

Prepending a dollar symbol to $TYPE escapes it.

Reference:

  • Variable Substitution in Compose
like image 166
Oluwafemi Sule Avatar answered Nov 23 '25 00:11

Oluwafemi Sule