Docker Secrets
Docker secrets are a way to deliver sensitive data such as passwords and tokens to containers without baking them into images, environment variables, or committed files. They cover build-time secret mounts and runtime file-based secrets.
Where secrets leak
The usual mistakes are ENV DB_PASSWORD=... or ARG TOKEN=... in a Dockerfile, hardcoded values in a Compose file, or COPY .env .. Each stores the secret in image metadata, layers, or version control, where docker history or a registry pull can expose it.
Build-time: BuildKit secret mounts
# syntax=docker/dockerfile:1FROM node:20-alpineWORKDIR /appCOPY package.json package-lock.json ./RUN --mount=type=secret,id=npm_token \ NPM_TOKEN=$(cat /run/secrets/npm_token) npm ciCOPY . .CMD ["node", "server.js"]docker buildx build --secret id=npm_token,src=$HOME/.secrets/npm-token -t myapp:1.0 .The secret exists only during that RUN step and is not stored in any layer.
Runtime: file-based secrets
services: postgres: image: postgres:16-alpine environment: POSTGRES_PASSWORD_FILE: /run/secrets/db_password secrets: - db_password secrets: db_password: file: ./secrets/db_password.txtInside the container, the value is readable at /run/secrets/db_password. In Swarm, secrets are stored encrypted in the cluster, delivered to nodes that run the service, and mounted in memory.
printf 'S3cureValue' | docker secret create db_password -docker service create --name api --secret db_password registry.example.com/payment-api:v3.1.0Production sources
Teams also fetch secrets at startup from AWS Secrets Manager, HashiCorp Vault, or Kubernetes Secrets backed by an external store. Prefer files over environment variables, since variables show up in docker inspect and many crash reports.
SecurityIf a secret reached a pushed image, rotate it first, then clean up. Deleting the image does not remove copies others already pulled.
Common MistakeBelieving a later
RUN unsetorrmremoves a secret. The earlier layer still contains it.
Frequently Asked Questions
Why is ENV for secrets unsafe even in a private image?
ENV values are stored in image metadata and visible with docker history or docker inspect to anyone who can pull the image. Later instructions cannot remove them from earlier layers.
How do build-time and runtime secrets differ?
Build-time secrets use BuildKit mounts that exist only during one RUN step. Runtime secrets are delivered as files, from Swarm secrets, Compose secrets, or an external secret manager, and kept out of the image.
Are Compose file secrets fully secure?
They keep values out of images and environment variables, but a file-based secret on a host is only as protected as that host. For production use a managed secret store and restrict access.