Variables with Shell-Style Default in docker-compose.yml
Posted on by Gentaro "hibariya" Terada
Today I learned that in docker-compose.yml
, a variable interpolation with a default can be expressed as ${VAR1:-default value}
like shell-style parameter expansion. With parameter expansion, you can do more than setting a default value such as modifying the parameter. However, the supported features in docker-compose.yml
are limited to two of them: to set a default variable or to make the parameter mandatory.
Let's define VAR_ALPHA
with a default value for the example
service.
services:
example:
image: debian
environment:
- VAR_ALPHA=${VAR_ALPHA:-the default value for VAR_ALPHA}
When running a container of the service, VAR_ALPHA
can be set by the same variable on the host machine. If the variable is null or empty, the default value will be used.
$ VAR_ALPHA='VAR_ALPHA from the host machine' docker-compose run --rm example bash -c 'echo $VAR_ALPHA'
VAR_ALPHA from the host machine
$ docker-compose run --rm example bash -c 'echo $VAR_ALPHA'
the default value for VAR_ALPHA
$ VAR_ALPHA='' docker-compose run --rm example bash -c 'echo $VAR_ALPHA'
the default value for VAR_ALPHA
docker-compose.yml
also supports making variables mandatory in this way. In the following example, the variable VAR_BRAVO
has to be set.
services:
example:
image: debian
environment:
- VAR_ALPHA=${VAR_ALPHA:-the default value for VAR_ALPHA}
- VAR_BRAVO=${VAR_BRAVO:?the variable VAR_BRAVO should be set} # this is mandatory
If VAR_BRAVO
is null or empty, docker-compose
will complain about that with the message you set and exit with 1.
$ VAR_BRAVO='VAR_ALPHA from the host machine' docker-compose run --rm example bash -c 'echo $VAR_BRAVO'
VAR_ALPHA from the host machine
$ docker-compose run --rm example bash -c 'echo $VAR_BRAVO'
ERROR: Missing mandatory value for "environment" option interpolating ['VAR_ALPHA=${VAR_ALPHA:-the default value for VAR_ALPHA}', 'VAR_BRAVO=${VAR_BRAVO:?the variable VAR_BRAVO should be set}'] in service "example": the variable VAR_BRAVO should be set
$ VAR_BRAVO='' docker-compose run --rm example bash -c 'echo $VAR_BRAVO'
ERROR: Missing mandatory value for "environment" option interpolating ['VAR_ALPHA=${VAR_ALPHA:-the default value for VAR_ALPHA}', 'VAR_BRAVO=${VAR_BRAVO:?the variable VAR_BRAVO should be set}'] in service "example": the variable VAR_BRAVO should be set
.env
file can be used to set variables. The parameter expansion technique is also available here.
$ cat .env
VAR_BRAVO=${VAR_BRAVO:-the default value for VAR_BRAVO}
$ docker-compose run --rm example bash -c 'echo $VAR_BRAVO'
the default value for VAR_BRAVO