✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.2.5.1 Compose Secret Declaration

A focused guide to Compose Secret Declaration, connecting core concepts with practical Docker and container operations.

Compose secret declaration is the process of defining a secret under a Compose file's top-level secrets key, specifying where its sensitive content actually comes from, whether a local file or, in a Swarm context, an externally managed secret store.

Declaring a Secret From a Local File

The most common form for local development and single-host deployments sources a secret's content directly from a local file.

secrets:
  api-key:
    file: ./secrets/api-key.txt
Declaring an Externally Managed Secret

For secrets actually managed by Swarm's own secret store (or an equivalent external secret management system), the external option references that pre-existing secret instead of a local file.

secrets:
  api-key:
    external: true

This tells Compose the secret already exists in the underlying secret store and should simply be referenced, rather than created from a local file.

Attaching a Declared Secret to a Service

A declared secret becomes accessible to a service only once explicitly listed under that service's own secrets field.

services:
  api:
    secrets:
      - api-key

secrets:
  api-key:
    file: ./secrets/api-key.txt

Without this explicit attachment, a declared secret remains unused by any service, even though it's defined at the top level.

Specifying a Custom Target Filename

The name a secret's content appears under inside the container can be customized, rather than always matching the secret's declared name.

services:
  api:
    secrets:
      - source: api-key
        target: production-api-key.txt
Why Compose Secret Declaration Matters

Correctly declaring a secret — sourcing it appropriately for the deployment context and explicitly attaching it to the services that need it — is the foundation for actually benefiting from Compose's more careful handling of sensitive data, rather than falling back to a less protected mechanism like plain environment variables.