Overview and What You Will Learn
Docker secrets leak in three common ways: baked into image layers by COPY or RUN, passed as --build-arg values that are recorded in image history, or hardcoded in docker-compose.yml and committed to git. The fix is to use BuildKit secret mounts at build time and file-based secrets at runtime, so credentials never become part of an image or a repository.
In this lab you will:
- Pass credentials to
docker buildwith BuildKit secret mounts so they leave no trace in layers - Check an image for leaked secrets
- Mount runtime credentials as files with Compose secrets
- Use
.envfiles correctly and understand what they do not protect - Limit each service to only the secrets it needs
- Respond correctly when a secret has already leaked
Why This Matters in Production
Imagine a backend engineer at a food-delivery company like Swiggy running docker history on a production image and finding a database password in a RUN layer from months earlier. Anyone with pull access to the registry could have read it the whole time. That is why image layers must be treated as permanent and public to everyone who can pull them.
Image layers are cumulative and immutable. Deleting a secret in a later RUN step does not remove it from the earlier layer, so the only safe approach is to never write the secret into a layer at all.
Core Principles
Secrets can leak at build time and at runtime, and each stage has a safe and an unsafe pattern.
Three rules cover almost every case:
- Never put a secret in an image layer: No
COPYof credential files, noARGfor tokens. - Prefer files over environment variables at runtime: Files are not shown by
docker inspect. - Give each service only its own secrets: A compromised worker should not hold the payment key.
Detailed Step-by-Step Practical Lab
How to Pass Secrets at Build Time With BuildKit
A BuildKit secret mount exposes a secret to a single RUN instruction and writes nothing to the image. BuildKit is the default builder in current Docker releases, so no extra flag is needed.
FROM node:20-alpineWORKDIR /appCOPY package*.json ./ # The private registry credentials exist only while this command runsRUN --mount=type=secret,id=npmrc,target=/root/.npmrc \ npm ci --omit=dev COPY . .USER nodeCMD ["node", "server.js"]# Supply the secret from a file on the build machinedocker build \ --secret id=npmrc,src=$HOME/.npmrc \ -t swiggy-api:1.4.2 . # Or supply it from an environment variableexport NPM_TOKEN=npm_dummy_token_for_labdocker build --secret id=npm_token,env=NPM_TOKEN -t swiggy-api:1.4.2 .The unsafe patterns to avoid look like this:
# DO NOT DO THIS: the file stays in the layer even after it is deletedCOPY .npmrc /root/.npmrcRUN npm installRUN rm /root/.npmrc # DO NOT DO THIS: build args are recorded in image historyARG NPM_TOKENRUN npm config set //registry.npmjs.org/:_authToken=$NPM_TOKENHow to Check a Docker Image for Leaked Secrets
You check an image by reading its history and scanning its layers with a secret scanner. Do this before pushing to a shared registry and as a CI gate.
# Show every layer command in fulldocker history --no-trunc swiggy-api:1.4.2 | grep -i -E "token|password|secret|key" # Show environment variables baked into the image configdocker inspect swiggy-api:1.4.2 --format '{{ json .Config.Env }}' # Scan layers for credential patternstrivy image --scanners secret swiggy-api:1.4.2 # Inspect each layer's file contents interactivelydive swiggy-api:1.4.2How to Use Docker Compose Secrets at Runtime
Compose secrets mount a file into the container at /run/secrets/<name>, and the application reads the file instead of an environment variable. In Compose, file-based secrets are bind-mounted read-only from the host file, so host file permissions still matter.
# Create secret files in a gitignored folder next to the compose filemkdir -p secretsprintf 'postgres://api_user:Xk9mP2@10.0.1.50:5432/swiggy_prod' > secrets/db_url.txtprintf 'rzp_live_dummy_key_for_lab' > secrets/payment_key.txtchmod 600 secrets/*.txtecho "secrets/" >> .gitignoreservices: api: image: swiggy-api:1.4.2 secrets: - db_url - payment_key worker: image: swiggy-worker:1.4.2 secrets: # The worker needs the database only, not the payment key - db_url db: image: postgres:16-alpine environment: # Official images accept *_FILE variables that read from a secret file POSTGRES_PASSWORD_FILE: /run/secrets/db_password secrets: - db_password secrets: db_url: file: ./secrets/db_url.txt payment_key: file: ./secrets/payment_key.txt db_password: file: ./secrets/db_password.txt// Read the secret from its file at startup, not from process.envconst fs = require('fs'); const dbUrl = fs.readFileSync('/run/secrets/db_url', 'utf8').trim();const paymentKey = fs.readFileSync('/run/secrets/payment_key', 'utf8').trim();Compose can also pass a secret to a build without leaving it in the image:
services: api: build: context: . secrets: - npmrc secrets: npmrc: file: ./secrets/npmrcRememberIn Docker Swarm, secrets are encrypted at rest and mounted in memory (tmpfs). With plain Docker Compose they are bind-mounted files, so protect the source files and keep them out of git.
How to Use .env Files Correctly
A .env file keeps credentials out of your compose file and out of git, but it is plain text. Use it for local development values and commit only a sample with dummy data.
# .env (gitignored, local development only)DATABASE_URL=postgres://dev_user:devpass@localhost:5432/swiggy_devREDIS_URL=redis://localhost:6379NODE_ENV=development# .gitignore.env.env.*!.env.example# .env.example (committed, dummy values only)DATABASE_URL=postgres://user:password@localhost:5432/dbnameREDIS_URL=redis://localhost:6379NODE_ENV=developmentCommon MistakeTreating
.envas secure storage. It is not encrypted, and values you pass intoenvironment:still appear indocker inspect. For production, use Compose secrets or a manager such as AWS Secrets Manager or HashiCorp Vault.
How to Respond When a Secret Has Already Leaked
If a credential appeared in an image, a log, or a repository, treat it as compromised and rotate it first. Removing the image afterwards is cleanup, not a fix.
# 1. Rotate the credential at its source (database, API provider, registry)# 2. Rebuild the image using BuildKit secret mountsdocker build --secret id=npm_token,env=NPM_TOKEN -t swiggy-api:1.4.3 . # 3. Push the clean image and redeploydocker push registry.devops.in/swiggy-api:1.4.3 # 4. Delete the leaked tag and confirm nothing else references itdocker history --no-trunc registry.devops.in/swiggy-api:1.4.2 | grep -i tokenHow to Deliver Secrets From HashiCorp Vault to a Container
A Vault Agent sidecar authenticates to Vault, renders secrets into files on a shared in-memory volume, and keeps them refreshed. The application then reads files exactly as it would with Compose secrets, so it never needs Vault credentials or client code.
services: vault-agent: image: hashicorp/vault:1.18 command: ["vault", "agent", "-config=/vault/config/agent.hcl"] volumes: - ./vault:/vault/config:ro - rendered-secrets:/vault/rendered api: image: swiggy-api:1.4.2 volumes: - rendered-secrets:/run/vault:ro depends_on: - vault-agent volumes: rendered-secrets: driver_opts: type: tmpfs device: tmpfs# ./vault/agent.hclvault { address = "https://10.0.1.60:8200"} auto_auth { method "approle" { config = { role_id_file_path = "/vault/config/role_id" secret_id_file_path = "/vault/config/secret_id" } }} template { source = "/vault/config/db_url.ctmpl" destination = "/vault/rendered/db_url"}SecurityUse a narrowly scoped Vault policy and a short secret TTL for the AppRole, and never commit
role_idorsecret_idfiles. In Kubernetes, prefer the Vault Kubernetes auth method over AppRole.
Production Best Practices & Common Pitfalls
- Use BuildKit secret mounts for build credentials: Never use
ARGorCOPYfor tokens. - Prefer
*_FILEvariables and mounted files at runtime: They keep values out ofdocker inspectand crash reports. - Scope secrets per service: Declare only the secrets each service needs.
- Keep
.envout of git: Commit.env.examplewith dummy values. - Scan images in CI: Run
trivy image --scanners secretand a repository scanner such as gitleaks before release. - Rotate after any leak: Deleting an image does not help if anyone already pulled it.
- Use a real secrets manager in production: Docker secrets are a delivery mechanism, not a vault.
TipMake secret scanning a required pipeline step. A scanner that fails the build on a detected credential catches mistakes before they reach the registry.
SecurityEnvironment variables set with
docker run -eor Composeenvironment:are visible indocker inspect, readable by every process in the container, and often captured by crash reporters. Use file-based secrets for credentials.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Build with a secret file | docker build --secret id=mykey,src=keyfile . |
| Build with an env secret | docker build --secret id=mykey,env=MYKEY . |
| Read image history in full | docker history --no-trunc image |
| Show container env vars | docker inspect container --format '{{ json .Config.Env }}' |
| Scan an image for secrets | trivy image --scanners secret image |
| Check a mounted secret | docker exec container cat /run/secrets/name |
| Symptom | Likely cause | Fix |
|---|---|---|
Secret visible in docker history |
Used ARG or COPY |
Rotate it, rebuild with --mount=type=secret |
/run/secrets/name missing |
Service does not list the secret | Add it under that service's secrets: |
| Build cannot find the secret | id mismatch |
Match the Dockerfile id= to --secret id= |
| Secret committed to git | Secrets folder not ignored | Rotate, add to .gitignore, purge git history |