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.
1cat .env
2TAG=v1.5
3
4cat compose.yml
5services:
6 web:
7 image: "webapp:${TAG}"
1web:
2 env_file:
3 - 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 whichdocker compose
is run.
1db:
2 image: "postgres:${POSTGRES_VERSION}"
The order of environment variable precedence (highest to lowest) is as follows:
- Set using
docker compose run -e
in the CLI - Substituted from your shell
- Set using the
environment
attribute in the Compose file - Use of the
--env-file
argument in the CLI - Use of the
env_file
attribute in the Compose file - Set using an
.env
file placed at base of your project directory - Set in a container image in the ENV directive. Having any
ARG
orENV
setting in aDockerfile
evaluates only if there is no Docker Compose entry forenvironment
,env_file
orrun --env
.
For detailed example read here.