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 which docker compose is run.
1db:
2  image: "postgres:${POSTGRES_VERSION}"

The order of environment variable precedence (highest to lowest) is as follows:

  1. Set using docker compose run -e in the CLI
  2. Substituted from your shell
  3. Set using the environment attribute in the Compose file
  4. Use of the --env-file argument in the CLI
  5. Use of the env_file attribute in the Compose file
  6. Set using an .env file placed at base of your project directory
  7. Set in a container image in the ENV directive. Having any ARG or ENV setting in a Dockerfile evaluates only if there is no Docker Compose entry for environmentenv_file or run --env.

For detailed example read here.