Jean Carlo Machado
Jean Carlo Machado

Reputation: 1618

Fallback for environment variables with docker-compose

Given the following configuration:

mysql:
    environment:
        MY_MYSQL_PORT:
    image: mysql
    ports:
        - "${MY_MYSQL_PORT}:3306"

There's a way to provide a fallback value for MY_MYSQL_PORT without relying on wrapper scripts? I already tested like bash ${MY_MYSQL_PORT-3306} but it doesn't work.

Upvotes: 27

Views: 12938

Answers (2)

Benjamin W. Bohl
Benjamin W. Bohl

Reputation: 340

An explanation in the Dockerfile documentation can be found at: https://docs.docker.com/engine/reference/builder/#environment-replacement

To quote from there:

The ${variable_name} syntax also supports a few of the standard bash modifiers as specified below:

  • ${variable:-word} indicates that if variable is set then the result will be that value. If variable is not set then word will be the result.
  • ${variable:+word} indicates that if variable is set then word will be the result, otherwise the result is the empty string.

In all cases, word can be any string, including additional environment variables.

Escaping is possible by adding a \ before the variable: \$foo or \${foo}, for example, will translate to $foo and ${foo} literals respectively.

Upvotes: 9

Alexander Heimbuch
Alexander Heimbuch

Reputation: 677

They implemented that feature with compose 1.9 release:

Added support for shell-style inline defaults in variable interpolation.

The supported forms are ${FOO-default} (fall back if FOO is unset) and ${FOO:-default} (fall back if FOO is unset or empty).

Release Notes Docker Compose 1.9

Upvotes: 39

Related Questions