Sub topic 7
Keeping Secrets Out of Images and Environment Variables
This chapter assumes you can write a Dockerfile, build and run images, and read basic Linux file permissions. It covers where secrets leak in Docker workflows and how to avoid each leak. A secret is any value that grants access: an API key, a registry token, a database password, a private key.
Why Images Leak Secrets
An image is a stack of layers. Each layer is a tarball of filesystem changes, and anyone who can pull the image can read every layer. Image metadata, including build arguments and environment variables, is also readable. Deleting a file in a later layer does not remove it from the earlier layer that added it.
The common leak paths are:
| Leak path | Why it leaks | Who can see it |
|---|---|---|
| `COPY .env /app/.env` | The file is stored in a layer | Anyone who can pull the image |
| `ARG TOKEN` used in `RUN` | The value is recorded in the build history | Anyone with the image |
| `ENV TOKEN=...` | The value is stored in image config and every container | Anyone with the image or `docker inspect` access |
| `RUN echo $TOKEN > file; rm file` | The file persists in the earlier layer | Anyone with the image |
| `COPY . .` without `.dockerignore` | Local `.env`, `.git`, and key files get copied | Anyone with the image |
Seeing the Problem
You can confirm a leak yourself. Build an image that passes a token as a build argument:
FROM alpine:3.20
ARG API_TOKEN
RUN echo "token length: ${#API_TOKEN}" > /tmp/infodocker build --build-arg API_TOKEN=s3cr3t-value -t leaky:1.0 .
docker history --no-trunc leaky:1.0The history output includes the ARG value in the recorded command for that step. Never use ARG or ENV for secrets, even for values that only matter at build time.
To inspect file leaks, export the image and list its layers:
docker save leaky:1.0 -o leaky.tar
tar -tf leaky.tarEach layer is a separate archive. Extracting them shows every file that was ever added.
Build-Time Secrets with BuildKit
Sometimes a build needs a credential, for example a token to install packages from a private registry. BuildKit, Docker's build engine, provides secret mounts for this. A secret mount exposes a file at /run/secrets/<id> for the duration of one RUN step. It is never written to a layer, and it does not appear in the build history.
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci
COPY . .
USER node
CMD ["node", "server.js"]Supply the secret from a local file when you build:
docker build --secret id=npm_token,src=./npm_token.txt -t myapp:1.0 .The id in the Dockerfile must match the id on the command line. The variable NPM_TOKEN exists only in that one command's environment, so it does not persist into the image.
Other Build-Time Options
--secret id=name,env=VAR_NAMEreads the secret from an environment variable on the build host instead of a file. Use it in CI where secrets arrive as environment variables.--mount=type=sshforwards your SSH agent into aRUNstep, so you can clone private repositories without copying a private key into the image.- A multi-stage build can isolate a credential in a throwaway stage. This helps, but it is weaker than a secret mount. Layers of the discarded stage still exist in the local build cache and in any image you tag from that stage.
Keep Secrets Out of the Build Context
The build context is the directory you send to the builder. If a .env file or private key sits in it, a broad COPY . . places it in the image. A .dockerignore file excludes paths from the context:
.env
.env.*
*.pem
*.key
.git
.aws
.npmrc
node_modulesThis is a safety net, not a substitute for secret mounts. Review it when you add new credential files to a project.
Runtime Secrets
A running container also needs secrets, such as database passwords. The options differ in how well they limit exposure.
Environment Variables
Passing a secret with docker run -e DB_PASSWORD=... is easy, and it is the weakest option. The value:
- is shown by
docker inspectto anyone who can reach the daemon, - is readable from
/proc/<pid>/environby processes with the same user or by root on the host, - is inherited by every child process,
- often appears in crash dumps, debug endpoints, and logs that print the environment,
- is saved in shell history if you type it on the command line.
Environment variables are acceptable for non-sensitive configuration. For secrets, prefer files.
Files Mounted at Runtime
A file mounted into the container avoids most of those exposures. The application reads it at startup:
docker run -d --name web \
--read-only --tmpfs /tmp \
-v /etc/myapp/db_password:/run/secrets/db_password:ro \
myapp:1.0Set strict permissions on the host file, and make sure the container's user can read it but nothing else can. Many official images support a _FILE convention. For example, the postgres image reads the password from the path in POSTGRES_PASSWORD_FILE.
docker run -d --name db \
-e POSTGRES_PASSWORD_FILE=/run/secrets/db_password \
-v /etc/myapp/db_password:/run/secrets/db_password:ro \
postgres:16Orchestrator Secrets
Docker Swarm and Docker Compose both have a secrets feature. Compose can mount a file as a secret under /run/secrets/:
services:
web:
image: myapp:1.0
secrets:
- db_password
secrets:
db_password:
file: ./db_password.txtIn Swarm, secrets are stored encrypted in the cluster's Raft log and delivered to containers over mutual TLS. They are mounted in an in-memory filesystem, so they are never written to the node's disk. In plain Compose, the secret is a bind mount of a local file, so its protection is only as good as the file's permissions.
For larger setups, use a dedicated secret manager such as HashiCorp Vault, AWS Secrets Manager, or your cloud provider's equivalent. The application, or a sidecar process, fetches secrets at startup using a short-lived identity. This gives you rotation, audit logs, and access control that a mounted file lacks.
Comparing the Options
| Approach | Stored in image | Visible in `docker inspect` | Rotation | Use for |
|---|---|---|---|---|
| `ENV` or `ARG` in Dockerfile | Yes | Yes | Rebuild image | Never for secrets |
| `docker run -e` | No | Yes | Restart container | Non-secret config |
| Mounted file | No | Only the mount path | Replace file, restart or reload | Single-host deployments |
| Swarm or Compose secret | No | Only the secret name | Create new secret, update service | Small clusters |
| Secret manager | No | No | Automatic, with audit | Production systems |
| BuildKit secret mount | No | Not applicable | Per build | Build-time credentials |
Edge Cases and Gotchas
- Secrets already committed to a registry. Deleting the tag does not make the leak safe. Assume the secret is compromised and rotate it first, then rebuild the image.
- Build cache. Secrets copied with
COPYstay in the local cache and in any cache you export to a registry. Prune caches after a leak, and rotate the secret. - Logging the environment. Frameworks that dump configuration on error can print secrets. Check what your application logs.
- Shell history and process lists. A secret typed as
--build-argor-eappears in shell history and sometimes inpsoutput on the host. Read secrets from files or standard input instead. - Scanning for leaks. Secret scanners such as
trufflehogorgitleakscan detect credentials in your repository and, with some tools, in image layers. Run them in CI. - Application memory. Once the application has loaded a secret, a memory dump can expose it. Limit who can run
docker execand read process memory, as covered in the chapters on capabilities and daemon security.
Practical Checklist
- Add
.dockerignorewith credential files before the first build. - Use
RUN --mount=type=secretfor every build-time credential. - Never use
ARGorENVfor secret values. - Mount runtime secrets as read-only files, or fetch them from a secret manager.
- Scan images and repositories for secrets in CI.
- Rotate any secret that was ever baked into an image, even briefly.
Exercise
A Dockerfile contains ARG NPM_TOKEN, then RUN echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc && npm ci && rm .npmrc. A teammate says the rm removes the secret. Name two places the token is still exposed, and describe the fix.
Show answer
The token appears in the build history, because ARG values used in a RUN step are recorded (visible with docker history --no-trunc). The .npmrc file also remains in the layer created by the RUN step's earlier filesystem changes in some workflows, and in the build cache, so removing it in the same step does not guarantee the secret is gone from every stored artifact. The fix is a BuildKit secret mount: RUN --mount=type=secret,id=npm_token NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci, built with docker build --secret id=npm_token,src=./npm_token.txt .. Rotate the already-exposed token.
Exercise
Why is mounting a file at /run/secrets/db_password better than docker run -e DB_PASSWORD=... for a production database credential?
Show answer
With -e, the value appears in docker inspect output, in /proc/<pid>/environ, in child processes, and often in logs or crash dumps. A read-only mounted file is not shown by docker inspect (only the mount path is), can be limited by file permissions, and is read by the application only when needed. A secret manager is better still, because it adds rotation and audit logging.