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 compose is run.
db:
  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.

Written on 2023-12-05 09:40:00 +0700 Edited on 2024-03-11 03:53:00 +0700