Skip to main content

Securing Docker Secrets in Images and Compose

Keep passwords and API keys out of Docker images and Compose files with BuildKit secret mounts, Compose secrets, and safe .env handling.

44 Terms

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 build with 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 .env files 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.

flowchart TD subgraph Build B1[ARG or COPY of secret] --> B2[Leaks into image history] B3[BuildKit secret mount] --> B4[No trace in any layer] end subgraph Runtime R1[Hardcoded environment value] --> R2[Visible in docker inspect] R3[Compose secrets file] --> R4[Read from run secrets path] end classDef bad fill:#FEE2E2,color:#1E293B classDef good fill:#D1FAE5,color:#1E293B class B1,B2,R1,R2 bad class B3,B4,R3,R4 good

Three rules cover almost every case:

  1. Never put a secret in an image layer: No COPY of credential files, no ARG for tokens.
  2. Prefer files over environment variables at runtime: Files are not shown by docker inspect.
  3. 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.

Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
# The private registry credentials exist only while this command runs
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
npm ci --omit=dev
COPY . .
USER node
CMD ["node", "server.js"]
Bash
# Supply the secret from a file on the build machine
docker build \
--secret id=npmrc,src=$HOME/.npmrc \
-t swiggy-api:1.4.2 .
# Or supply it from an environment variable
export NPM_TOKEN=npm_dummy_token_for_lab
docker build --secret id=npm_token,env=NPM_TOKEN -t swiggy-api:1.4.2 .

The unsafe patterns to avoid look like this:

Dockerfile
# DO NOT DO THIS: the file stays in the layer even after it is deleted
COPY .npmrc /root/.npmrc
RUN npm install
RUN rm /root/.npmrc
# DO NOT DO THIS: build args are recorded in image history
ARG NPM_TOKEN
RUN npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN
How 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.

Bash
# Show every layer command in full
docker history --no-trunc swiggy-api:1.4.2 | grep -i -E "token|password|secret|key"
# Show environment variables baked into the image config
docker inspect swiggy-api:1.4.2 --format '{{ json .Config.Env }}'
# Scan layers for credential patterns
trivy image --scanners secret swiggy-api:1.4.2
# Inspect each layer's file contents interactively
dive swiggy-api:1.4.2
How 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.

Bash
# Create secret files in a gitignored folder next to the compose file
mkdir -p secrets
printf 'postgres://api_user:Xk9mP2@10.0.1.50:5432/swiggy_prod' > secrets/db_url.txt
printf 'rzp_live_dummy_key_for_lab' > secrets/payment_key.txt
chmod 600 secrets/*.txt
echo "secrets/" >> .gitignore
YAML
services:
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
JAVASCRIPT
// Read the secret from its file at startup, not from process.env
const 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:

YAML
services:
api:
build:
context: .
secrets:
- npmrc
secrets:
npmrc:
file: ./secrets/npmrc
Remember

In 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.

Bash
# .env (gitignored, local development only)
DATABASE_URL=postgres://dev_user:devpass@localhost:5432/swiggy_dev
REDIS_URL=redis://localhost:6379
NODE_ENV=development
Bash
# .gitignore
.env
.env.*
!.env.example
Bash
# .env.example (committed, dummy values only)
DATABASE_URL=postgres://user:password@localhost:5432/dbname
REDIS_URL=redis://localhost:6379
NODE_ENV=development
Common Mistake

Treating .env as secure storage. It is not encrypted, and values you pass into environment: still appear in docker 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.

Bash
# 1. Rotate the credential at its source (database, API provider, registry)
# 2. Rebuild the image using BuildKit secret mounts
docker build --secret id=npm_token,env=NPM_TOKEN -t swiggy-api:1.4.3 .
# 3. Push the clean image and redeploy
docker push registry.devops.in/swiggy-api:1.4.3
# 4. Delete the leaked tag and confirm nothing else references it
docker history --no-trunc registry.devops.in/swiggy-api:1.4.2 | grep -i token
How 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.

YAML
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
HCL
# ./vault/agent.hcl
vault {
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"
}
Security

Use a narrowly scoped Vault policy and a short secret TTL for the AppRole, and never commit role_id or secret_id files. In Kubernetes, prefer the Vault Kubernetes auth method over AppRole.

Production Best Practices & Common Pitfalls

  • Use BuildKit secret mounts for build credentials: Never use ARG or COPY for tokens.
  • Prefer *_FILE variables and mounted files at runtime: They keep values out of docker inspect and crash reports.
  • Scope secrets per service: Declare only the secrets each service needs.
  • Keep .env out of git: Commit .env.example with dummy values.
  • Scan images in CI: Run trivy image --scanners secret and 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.
Tip

Make secret scanning a required pipeline step. A scanner that fails the build on a detected credential catches mistakes before they reach the registry.

Security

Environment variables set with docker run -e or Compose environment: are visible in docker 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

Resources

Explore More in Docker Security and Production Practices

All 5 Topics

Frequently Asked Questions

Is Securing Docker Secrets in Images and Compose free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Securing Docker Secrets in Images and Compose topic cover?

Keep passwords and API keys out of Docker images and Compose files with BuildKit secret mounts, Compose secrets, and safe .env handling.

Found a mistake, an outdated step or a broken link?