Variables and secrets

How to pass settings without putting a password into the image.

Settings that differ between machines are passed through environment variables: the database address, the log level, external keys. The image stays the same, and the environment is set at start. In Compose variables go into the environment section or into a separate file via env_file.

Compose also reads the .env file next to compose.yaml and substitutes its values into the file itself: ${DB_PASSWORD} is replaced with the value from .env. The .env file itself is added to .gitignore and .dockerignore, and the repository keeps an example with empty values, for example .env.example.

services:
  db:
    image: postgres:16.4
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD}
  api:
    build: .
    env_file: api.env
DB_PASSWORD=change-me

The second block is the contents of the .env file on the server. The repository holds only compose.yaml and an example without real values.

The main rule: secrets never go into the image. A line ENV API_KEY=... in a Dockerfile, or a key file copied with COPY, stays in the image layers forever, and anyone who gets the image can read it, even if the file is deleted in the next step. ARG does not work either: build argument values are visible in docker history. If a key is needed during the build, BuildKit secrets (RUN --mount=type=secret) are used; they are not stored in layers.

A common mistake is to print all environment variables to the log at start-up “for debugging”. The passwords end up in docker logs and in the log system. Another mistake is to check a secret on the server with docker inspect and forward the output to a colleague: it shows all the container's variables. Secrets are passed so that they never appear in the image, the logs or the repository.

Practice

  1. Where to keep the password

    Where should the database password for a Docker Compose project be kept?

    • In ENV in the Dockerfile
    • Directly in compose.yaml in the repository
    • In the .env file on the server that never goes into git
    • In the project README
  2. Where secrets leak

    In which cases does a secret become available to anyone who has the image? Mark all.

    • ENV API_KEY=... in the Dockerfile
    • COPY secret.json and then RUN rm secret.json
    • An ARG value used in RUN
    • A variable passed at start with -e
  3. The substitution file

    What is the name of the file next to compose.yaml that Compose reads by default for ${...} values?