TExcelTAD
Home › Docker Compose › Configs & Secrets

Configs & Secrets

Most apps need two kinds of input besides code: configuration (an nginx server block, a log level, feature flags) and secrets (database passwords, API keys, TLS private keys). You can pass both through environment variables or bind mounts, but Compose has first-class elements for them: top-level configs: and secrets:, mounted into services as files. The same keys work in Swarm, where they become encrypted, cluster-managed objects.

Why files instead of environment variables?

Environment variables are convenient, but for secrets they leak in many ways:

  • docker inspect shows every variable of a container in plain text.
  • Child processes inherit the whole environment, including tools you shell out to.
  • Crash reporters and debug pages love to dump the environment.
  • They end up in shell history and CI logs when set on the command line.

A secret mounted as a file under /run/secrets/ is visible only inside the container, only to processes that read it, and doesn't show up in docker inspect's Env list.

Declaring configs

A config is a read-only file that Compose places in the container. Its source can be a file, inline content, or an environment variable.

compose · try it yourself
# $ docker compose config --no-path-resolution
services:
  web:
    image: nginx:1.29
    configs:
      - source: site
        target: /etc/nginx/conf.d/default.conf
        mode: 0444
      - app_settings

configs:
  site:
    file: ./nginx/default.conf
  app_settings:
    content: |
      log_level = ${LOG_LEVEL:-info}
      region = eu-west-1
WARN[0000] service "web": configs.site.mode: mode is not supported outside Swarm mode and will be ignored
name: demo
services:
  web:
    configs:
      - source: site
        target: /etc/nginx/conf.d/default.conf
        mode: "0444"
      - source: app_settings
    image: nginx:1.29
    networks:
      default: null
networks:
  default:
    name: demo_default
configs:
  app_settings:
    name: demo_app_settings
    content: |
      log_level = info
      region = eu-west-1
  site:
    name: demo_site
    file: ./nginx/default.conf

What to notice:

  • content is interpolated: ${LOG_LEVEL:-info} was replaced by info because the variable isn't set. Handy for generating small config files from variables, no template engine needed.
  • The short form - app_settings keeps no target: Compose mounts it at /app_settings in the container's root. Almost always you want a long-form target.
  • Configs are named with the project prefix (demo_site), like volumes.
  • The WARN line: plain Compose bind-mounts the file and keeps its permissions on the host, so mode is honoured only by Swarm. config keeps the key but tells you it will be ignored.

Declaring secrets

Secrets look almost the same. Their default target is /run/secrets/<name>, which is a tmpfs in Swarm and a bind-mounted file with plain Compose.

compose · try it yourself
# $ docker compose config --no-path-resolution
services:
  api:
    image: ghcr.io/acme/api:3.0
    environment:
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
      - source: payments_key
        target: stripe_key
        uid: "1000"
        gid: "1000"
        mode: 0400

secrets:
  db_password:
    file: ./secrets/db_password.txt
  payments_key:
    environment: PAYMENTS_KEY

# --- .env
PAYMENTS_KEY=sk_test_51Hx_example
WARN[0000] service "api": secrets.payments_key.gid: gid is not supported outside Swarm mode and will be ignored
WARN[0000] service "api": secrets.payments_key.mode: mode is not supported outside Swarm mode and will be ignored
WARN[0000] service "api": secrets.payments_key.uid: uid is not supported outside Swarm mode and will be ignored
name: demo
services:
  api:
    environment:
      DB_PASSWORD_FILE: /run/secrets/db_password
    image: ghcr.io/acme/api:3.0
    networks:
      default: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
      - source: payments_key
        target: stripe_key
        uid: "1000"
        gid: "1000"
        mode: "0400"
networks:
  default:
    name: demo_default
secrets:
  db_password:
    name: demo_db_password
    file: ./secrets/db_password.txt
  payments_key:
    name: demo_payments_key
    environment: PAYMENTS_KEY

Three details in this output:

  1. The short form was expanded to target: /run/secrets/db_password, while the relative target stripe_key is kept as written and means /run/secrets/stripe_key in the container.
  2. The value of PAYMENTS_KEY from .env does not appear. The secret only records where the value comes from (environment: PAYMENTS_KEY). Pasting docker compose config output into a ticket won't leak it. (Interpolated values elsewhere in the file, like environment: entries, would appear.)
  3. The warnings: uid, gid and mode are Swarm features. Plain Compose bind-mounts the secret file as it is on the host, so it ignores them (and says so), but they keep the file ready for docker stack deploy.

Warning: keep secret files out of Git. Add secrets/ to .gitignore and to .dockerignore, so they don't end up in an image either.

The _FILE convention

How does the app find the password? Many official images (postgres, mysql, mariadb, wordpress) accept <NAME>_FILE variables: POSTGRES_PASSWORD_FILE=/run/secrets/db_password tells the entrypoint to read the value from that file. Your own apps can follow the same convention with a few lines:

python · try it yourself
import os

# simulate the container: a secret file and the environment Compose sets
FILES = {"/run/secrets/db_password": "s3cr3t-from-file\n"}
ENV = {"DB_PASSWORD_FILE": "/run/secrets/db_password", "API_TOKEN": "plain-env-token"}

def read_setting(name, env=ENV, files=FILES):
    """Prefer NAME_FILE (a mounted secret), fall back to NAME, else fail."""
    path = env.get(f"{name}_FILE")
    if path:
        if path not in files:
            raise RuntimeError(f"{name}_FILE points to {path}, which does not exist")
        return files[path].rstrip("\n"), f"file {path}"
    if name in env:
        return env[name], "environment"
    raise RuntimeError(f"{name} is not configured")

for name in ["DB_PASSWORD", "API_TOKEN", "SMTP_PASSWORD"]:
    try:
        value, source = read_setting(name)
        print(f"{name:<14} from {source:<32} = {value[:3]}***")
    except RuntimeError as e:
        print(f"{name:<14} error: {e}")
DB_PASSWORD    from file /run/secrets/db_password    = s3c***
API_TOKEN      from environment                      = pla***
SMTP_PASSWORD  error: SMTP_PASSWORD is not configured

Strip the trailing newline: text editors add one, and a password with \n at the end won't match.

Sources compared

Source Configs Secrets Notes
file: ./path yes yes most common; path relative to the project directory
content: | yes no inline, interpolated; Compose only (not Swarm)
environment: VAR yes yes value from the Compose environment (shell or .env)
external: true yes yes object already exists; Swarm only, plain Compose can't use it
name: yes yes exact name instead of <project>_<key>

Compose vs Swarm

With plain Compose, configs and secrets are just files mounted into the container: no encryption, no access control beyond file permissions. The same file under docker stack deploy becomes real Swarm objects stored encrypted in the Raft log and delivered only to nodes that run the service. Not every Compose feature is accepted there, though:

compose · try it yourself
# $ docker stack config -c compose.yaml
services:
  api:
    image: ghcr.io/acme/api:3.0
    configs: [app_settings]
    secrets: [db_password]

configs:
  app_settings:
    content: |
      region = eu-west-1

secrets:
  db_password:
    external: true
configs.app_settings: additional property 'content' is not allowed

Swarm rejects inline content; it wants a file (or an external object created with docker config create). See Swarm Configs and Swarm Secrets for the full lifecycle, including rotation.

Changing a config

A config or secret is read when the container is created. Editing ./nginx/default.conf doesn't affect a running container; docker compose up -d notices the changed content and recreates the service. Most servers also need a reload to read a new file, which recreation gives you for free. A quick model of that decision:

python · try it yourself
import hashlib

def digest(text):
    return hashlib.sha256(text.encode()).hexdigest()[:12]

running = {"web": digest("server { listen 80; }")}

def plan(service, new_content):
    new = digest(new_content)
    if running[service] == new:
        return f"{service}: config {new} unchanged -> Running (nothing to do)"
    return f"{service}: config {running[service]} -> {new} -> Recreate"

print(plan("web", "server { listen 80; }"))
print(plan("web", "server { listen 80; gzip on; }"))
web: config b9dc21d0a893 unchanged -> Running (nothing to do)
web: config b9dc21d0a893 -> 8e6fe2e2da78 -> Recreate

Learn more: Environment & env_file · Compose Security · Kubernetes Secrets · ConfigMaps

Test yourself

Where is a secret declared as - db_password (short syntax) mounted inside the container?

  1. /db_password
  2. /etc/secrets/db_password
  3. /run/secrets/db_password
  4. In the environment variable DB_PASSWORD

Why are secret files preferred over environment variables for passwords?

  1. Files are encrypted by Compose
  2. Environment variables are visible in docker inspect, inherited by child processes and often dumped in logs
  3. Environment variables can't hold special characters
  4. Files are faster

Which config source does docker stack config reject?

  1. file:
  2. external: true
  3. content:
  4. name: