Sub topic 14
Keeping Secrets Out of Layers
This chapter assumes you can write a multi-stage Dockerfile, use docker history, and run containers with docker run. It also assumes you know that each instruction can create a layer. Here you will see how credentials end up in images, how to check for them, and how BuildKit secret mounts avoid the problem.
Why deleting a secret does not remove it
A layer is an immutable record of filesystem changes. A later layer can hide a file from the running container, but the earlier layer that contains it is still part of the image. Anyone who pulls the image can unpack that layer.
This Dockerfile looks safe, but it is not:
FROM node:20-slim
WORKDIR /app
COPY .npmrc ./
COPY package*.json ./
RUN npm ci
RUN rm .npmrcThe COPY .npmrc ./ layer holds your registry token. The RUN rm .npmrc layer only adds a marker saying the file is deleted. The final image ships both layers.
You can confirm this on an image you built. Save it to a tarball, unpack it, and search for the token text:
docker build -t myapp:bad .
mkdir saved
docker save myapp:bad | tar -x -C saved
grep -rla "_authToken" savedIf grep lists a file, the secret is in the image. Layer blobs from docker save are usually stored uncompressed, which is why a plain grep works. If your Docker version stores them compressed, extract each layer first.
Other ways secrets leak
Copying a file is the obvious case. These are easier to miss.
Build arguments
ARG looks like a safe way to pass a token, but the value is recorded in the image metadata.
FROM node:20-slim
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc \
&& npm ci \
&& rm .npmrcdocker build --build-arg NPM_TOKEN=abc123 -t myapp:bad .
docker history --no-trunc myapp:badThe docker history output shows the RUN instruction together with the build argument values. Removing the file inside the same RUN avoids the leftover file layer, but not the history entry.
Environment variables
ENV writes the value into the image configuration. Every container started from the image sees it, and docker inspect prints it. Never set a real secret with ENV.
Files copied with a broad COPY
COPY . . takes everything in the build context, including .env files, .git history, and key files. Your .dockerignore from earlier chapters is the first defence:
.git
.env
*.pem
*.key
.npmrcA .dockerignore entry only protects you from files you remember to list. Treat it as a safety net, not as your secrets strategy.
Intermediate stages
Multi-stage builds help here. Only instructions in the final stage become the final image's layers and history. If the secret is used only in a build stage and you copy just the built output forward with COPY --from, the final image does not contain it. Two caveats apply:
- Anything you push from a build stage, for example an image built with
--target build, contains that stage's layers. Do not publish those images. - The local build cache still holds the layers. Multi-stage builds protect the image you ship, not the machine you build on.
Multi-stage builds are a useful second barrier. They are not a substitute for handling the secret correctly in the first place.
Secret mounts: the right way to use a secret at build time
BuildKit can mount a secret into a single RUN instruction. The file exists only while that command runs. It is not written to any layer, and it does not appear in docker history.
# syntax=docker/dockerfile:1
FROM node:20 AS build
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
COPY . .
RUN npm run build
FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]You supply the secret on the command line:
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:small .The id links the --mount in the Dockerfile to the --secret flag. Without target, the file appears at /run/secrets/<id>. Each RUN that needs the secret must request the mount, so the final stage above mounts it again for the production install.
You can also read a secret from an environment variable on your machine instead of a file:
export NPM_TOKEN=abc123
docker build --secret id=npm_token,env=NPM_TOKEN -t myapp:small .Inside the build, use it within one command, for example RUN --mount=type=secret,id=npm_token sh -c 'NPM_TOKEN=$(cat /run/secrets/npm_token) ./install.sh'. Never write the value to a file in the image.
SSH mounts for private repositories
If a build must clone a private Git repository, forward your SSH agent instead of copying a private key:
# syntax=docker/dockerfile:1
FROM alpine:3.20 AS fetch
RUN apk add --no-cache git openssh-client
RUN mkdir -p -m 0700 /root/.ssh && ssh-keyscan github.com >> /root/.ssh/known_hosts
RUN --mount=type=ssh git clone [email protected]:example/private-repo.git /srcdocker build --ssh default -t myapp:fetch .The agent socket is available only during that RUN. The key never enters a layer. The ssh-keyscan line trusts whatever key the network returns at build time. For stricter setups, pin the host's known fingerprint instead.
Comparing the options
| Mechanism | Appears in layers? | Appears in `docker history`? | Verdict for secrets |
|---|---|---|---|
| `COPY` then `rm` | Yes | File name only | Never use |
| `ARG` | No file, but value in metadata | Yes | Never use |
| `ENV` | In image config | Yes | Never use |
| `--mount=type=secret` | No | No | Use for build-time secrets |
| `--mount=type=ssh` | No | No | Use for private Git access |
Runtime secrets are a separate problem
Build-time secrets are credentials the build needs, such as a private registry token. Runtime secrets are credentials the running app needs, such as a database password. Do not bake runtime secrets into the image at all. Supply them when the container starts:
docker run --rm \
-v "$PWD/db_password.txt:/run/secrets/db_password:ro" \
myapp:smallThe application reads /run/secrets/db_password at startup. Orchestrators such as Docker Swarm and Kubernetes provide the same idea through their own secret objects. Passing values with -e or --env-file is simpler, but those values are visible through docker inspect and in the process environment, so prefer mounted files when you can.
Checking an image before you publish
- Run
docker history --no-trunc IMAGEand look for tokens or passwords in instructions. - Run
docker inspect IMAGEand check theEnvsection. - Run
docker save IMAGE | tar -x -C savedandgrep -rlafor known secret strings. - Optionally add a scanner such as Trivy or Gitleaks to your pipeline. Scanners find common secret formats, but they cannot recognise arbitrary strings.
Common mistakes
- Passing a token with
--build-argbecause "it is only for the build". It is stored in the image history. - Forgetting to repeat the secret mount in every
RUNthat needs it. The mount lasts for one instruction. - Writing the mounted secret to another path, for example copying
/run/secrets/npmrcinto the working directory. That creates a normal file in a layer. - Publishing the build-stage image, which keeps the compilers, the source code, and any files you copied in.
- Relying on
.dockerignorealone and then usingCOPY . .in a stage that also has credentials in the build context.
Exercise
A Dockerfile contains ARG DB_TOKEN, then RUN ./fetch-assets.sh "$DB_TOKEN", and the build is run with --build-arg DB_TOKEN=s3cret. The script does not store the token on disk. Is the token safe? If not, how do you fix it?
Show answer
It is not safe. The build argument value is recorded in the image metadata, and docker history --no-trunc shows it, even though no file contains it. Fix it by mounting the token as a secret for that one instruction: RUN --mount=type=secret,id=db_token sh -c './fetch-assets.sh "$(cat /run/secrets/db_token)"', and build with docker build --secret id=db_token,env=DB_TOKEN . (or src= pointing at a file). Then rotate the token if the old image was ever shared.
Exercise
Why does COPY .env . followed by RUN rm .env leave the secret in the image, and why does a multi-stage build help only if you do not publish the build stage?
Show answer
Each instruction creates its own immutable layer. The COPY layer contains .env, and the rm layer only records a deletion on top of it, so the final image still includes the first layer. In a multi-stage build, only the final stage's layers form the shipped image, so a secret used in a build stage is not in it as long as you copy forward only artifacts. If you push the build-stage image (for example one built with --target build), its layers, and the secret in them, are published.