log / docker compose variable
When creating a Docker Compose file, leveraging environment variables allows us to create a dynamic Docker Compose configuration based on the environment. We can either create a file named .env or use shell environment variables, as docker compose by default reads variables from these two sources.
cat .env
TAG=v1.5
cat compose.yml
services:
web:
image: "webapp:${TAG}"
web:
env_file:
- web-variables.env
- Substitute from the shell
It’s possible to use environment variables in your shell to populate values inside a Compose file. Compose uses the variable values from the shell environment in which
docker composeis run.
db:
image: "postgres:${POSTGRES_VERSION}"
The order of environment variable precedence (highest to lowest) is as follows:
- Set using
docker compose run -ein the CLI - Substituted from your shell
- Set using the
environmentattribute in the Compose file - Use of the
--env-fileargument in the CLI - Use of the
env_fileattribute in the Compose file - Set using an
.envfile placed at base of your project directory - Set in a container image in the ENV directive. Having any
ARGorENVsetting in aDockerfileevaluates only if there is no Docker Compose entry forenvironment,env_fileorrun --env.
For detailed example read here.