An environment variable is a named value a program can read. Compose can use variables in two places. It can substitute a value while reading the file, and it can pass values to a program inside a container.
Docker Compose · Lesson 5
Environment Variables
Learn to distinguish a value substituted into a Compose file from a value passed into a container.
Substituting a Value in the File
Save this as compose.env.yaml in your practice folder. In this file, ${PAGE_MODE:-demo} means to use PAGE_MODE when its value is set and nonempty and otherwise to use demo.
services:
toolbox:
image: busybox:1.36
environment:
PAGE_MODE: "${PAGE_MODE:-demo}"
Compose resolves the expression before creating the container. This is called interpolation. In other files you may see the same technique used to select a host port or image tag.
If PAGE_MODE is unset, which value appears in the rendered configuration?
Viewing the Resolved Value
A variable assignment before a command sets the variable for that invocation. Use it to see what a different value would do. The config command prints resolved settings and creates no container.
$ PAGE_MODE=review docker compose -p journey-env -f compose.env.yaml config
Look for PAGE_MODE: review under the service's environment. The value review is a demonstration setting. Keep secrets out of sample configuration and printed output.
The rendered file shows review. What has happened so far?
Passing a Value into the Container
The environment section passes the resolved setting into a new container. Use printenv to ask the program inside the one-off container to print that value.
$ PAGE_MODE=review docker compose -p journey-env -f compose.env.yaml run --rm toolbox printenv PAGE_MODE
Expect review. Interpolation selected the value. The environment entry delivered it to the container. A variable used only to choose a host port would not automatically become part of the program's environment.
Which action checks the value the program inside the toolbox receives?
Lesson complete
You finished Environment Variables
You can now tell the two uses of environment variables apart.
Read a default expression in a Compose file.
Inspect the resolved configuration before launching a container.
Check a value in the environment of the launched program.
Keep your learning progress
Create a free account to save this lesson and continue learning on any device.
Create a free account