Bash

Prevent Secret Leaks in Docker Builds with BuildKit Mounts

Your Docker build needs to fetch private dependencies from an internal npm registry, a private Go proxy, or a locked GitHub repository. If you pass your authentication token as a standard build argument using ARG, that secret gets permanently recorded into the image history and metadata layers.

text
$ docker history --no-trunc my-app:latest

IMAGE          CREATED         CREATED BY                                                                                                SIZE
e73a0c0f99b2   2 minutes ago   CMD ["node" "server.js"]                                                                                  0B
53b6eb4e8c11   2 minutes ago   RUN npm ci --omit=dev                                                                                     42.3MB
d123e4f5a6b7   3 minutes ago   ARG NPM_TOKEN=npm_7xK9910zAbCdEfGhIjKlMnOpQrStUvWxYz                                                      0B

Anyone with pull access to your container registry can run docker history or inspect image layers to extract that active token.

Why Build Arguments Leak Secrets

A common pattern for passing credentials looks simple. You declare an argument, build with --build-arg, and interpolate the variable in your install steps:

dockerfile
# Anti-pattern: Do not use this
FROM node:20-alpine
WORKDIR /app
ARG GITHUB_TOKEN
RUN echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" > .npmrc \
    && npm ci \
    && rm -f .npmrc
COPY . .
CMD ["node", "index.js"]

This pattern fails for two reasons.

First, Docker commits every ARG instruction directly into the image config manifest. It remains visible in docker history and docker inspect for the lifetime of that image tag, even if the value was never written to a file on disk.

Second, the filesystem modification in that RUN command does not delete the secret from older layers. The echo command creates a filesystem diff containing .npmrc. The rm -f command only marks the file as deleted in a subsequent layer. The raw bytes containing the token remain preserved inside the earlier tar archive of the image.

The proper fix uses BuildKit secret mounts. BuildKit mounts the secret into a temporary in-memory filesystem during the execution of a specific RUN command. The secret exists only inside that process, leaves no traces in filesystem diffs, and never registers in the build metadata.

Setting Up BuildKit Secret Mounts

To use secret mounts, your Docker engine needs BuildKit enabled. Modern Docker Desktop and Linux engine versions (23.0 and newer) enable BuildKit by default. If you run older versions, export DOCKER_BUILDKIT=1 in your shell.

Here is a secure implementation for an application that requires access to a private npm registry.

1. Write the Dockerfile Using Secret Mounts

Create your Dockerfile. Instead of ARG, use the --mount=type=secret flag on the RUN command:

dockerfile
# syntax=docker/dockerfile:1
FROM node:20-alpine AS builder

WORKDIR /app

# Copy dependency manifests first to leverage layer caching
COPY package.json package-lock.json ./

# Mount the secret file directly to the path where the client expects it
RUN --mount=type=secret,id=npmrc,target=/app/.npmrc \
    npm ci --ignore-scripts

COPY . .
RUN npm run build

# Final runtime stage
FROM node:20-alpine

WORKDIR /app
ENV NODE_ENV=production

COPY package.json package-lock.json ./
RUN --mount=type=secret,id=npmrc,target=/app/.npmrc \
    npm ci --omit=dev --ignore-scripts

COPY --from=builder /app/dist ./dist

USER node
CMD ["node", "dist/server.js"]

In this file, target=/app/.npmrc places the secret file at /app/.npmrc only while npm ci runs. Once the command completes, the file vanishes. It is never committed to the layer.

2. Supply the Secret During Build

Do not store your token in a tracked file. Store it in a local environment variable or an untracked local file like .npmrc.local.

If your secret lives in a local file:

bash
docker build --secret id=npmrc,src=.npmrc.local -t internal-api:latest .

If your secret lives in an environment variable named NPM_TOKEN, you can pass it directly without writing it to a temporary file:

bash
docker build --secret id=npmrc,env=NPM_TOKEN -t internal-api:latest .

When using env=VARIABLE_NAME, Docker creates a temporary file containing the value of that variable and mounts it to your target path.

Passing Raw Environment Variables Instead of Files

Sometimes a tool expects a secret directly in an environment variable rather than a configuration file. For example, some tools read GITHUB_TOKEN or AWS_SECRET_ACCESS_KEY directly from the process environment.

You can mount secrets directly as environment variables inside the RUN step without placing them in the build history:

dockerfile
# syntax=docker/dockerfile:1
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .

RUN --mount=type=secret,id=pypi_token,env=TWINE_PASSWORD \
    pip install --no-cache-dir -r requirements.txt

You run this build by passing the secret from your host environment:

bash
export TWINE_PASSWORD="pypi-AgEIcHlwaS5vcmcCJ..."
docker build --secret id=pypi_token,env=TWINE_PASSWORD -t worker:latest .

Inside that single RUN layer, the environment variable TWINE_PASSWORD is available. Downstream layers, child images, and docker inspect outputs will have no record that TWINE_PASSWORD ever existed.

Verifying the Fix

You need to verify two things: that the secret is absent from the metadata, and that the secret is absent from the image filesystem layers.

1. Check Metadata History

Run docker history on your built image:

bash
docker history internal-api:latest

The output should show the RUN command without any embedded tokens:

text
IMAGE          CREATED         CREATED BY                                                                                SIZE
5a4f78b21234   40 seconds ago  CMD ["node" "dist/server.js"]                                                             0B
9b8e7c6d5e4f   40 seconds ago  USER node                                                                                 0B
1a2b3c4d5e6f   41 seconds ago  COPY /app/dist ./dist # buildkit                                                          1.2MB
7f8e9d0c1b2a   42 seconds ago  RUN |0 /bin/sh -c npm ci --omit=dev --ignore-scripts # buildkit                           28.4MB

Notice the # buildkit tag and the absence of secret values in the command string.

2. Inspect the Layers for Leaked Files

Export the container filesystem to tar and search it directly for the secret string:

bash
# Save the image to a tar archive
docker save internal-api:latest -o /tmp/image.tar

# Search for the literal secret string across all internal tar layers
tar -xOf /tmp/image.tar | grep -a "npm_7xK9910zAbCdEfGhIjKlMnOpQrStUvWxYz"

If the string is absent, grep returns exit code 1 and produces no output. The secret was never written to any intermediate tar layer.

Edge Case 1: Docker Layer Cache Invalidation

Secret mounts do not invalidate the Docker build cache by default.

If your dependencies update in your private repository, but package.json and package-lock.json have not changed, Docker sees identical inputs for the cache key. It will reuse the cached layer from the previous build instead of running the RUN command with your secret mount again.

text
=> CACHED [builder 3/4] RUN --mount=type=secret,id=npmrc,target=/app/.npmrc npm ci

If you must force a fetch because upstream tags changed without a lockfile change, pass the --no-cache-filter flag targeting that specific stage:

bash
docker build --no-cache-filter builder --secret id=npmrc,src=.npmrc.local -t internal-api:latest .

This rebuilds the builder stage fresh without throwing away layer caches for earlier base steps.

Edge Case 2: Git Authentication and SSH Forwarding

If your project pulls private repositories through Git submodules or Git-based package dependencies (like git+ssh://[email protected]/...), do not pass raw SSH private keys as files or secrets.

Writing an SSH key into a container filesystem, even temporarily, risks file permissions errors. OpenSSH requires strict 0600 permissions on key files. If the mount lacks these, the SSH client refuses to read them.

Use SSH agent forwarding mounts instead:

dockerfile
# syntax=docker/dockerfile:1
FROM alpine:3.19

RUN apk add --no-cache git openssh-client

# Add host keys to prevent interactive host verification prompts
RUN mkdir -p -m 0700 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts

# Mount the host SSH socket directly
RUN --mount=type=ssh git clone [email protected]:internal-org/private-core.git /src/core

To run this build, ensure your local SSH agent has the necessary identity loaded, then pass the --ssh default flag:

bash
# Check if key is loaded locally
ssh-add -l

# If not, add it
ssh-add ~/.ssh/id_ed25519

# Build using the forwarded agent
docker build --ssh default -t service-runner:latest .

BuildKit connects to your local UNIX socket at $SSH_AUTH_SOCK. The container communicates with your host authentication agent over that pipe. The container signs the Git handshake requests, but the private key never enters the container filesystem or memory space.

Edge Case 3: Missing the BuildKit Syntax Directive

If you build an image containing --mount=type=secret on an engine that falls back to the legacy builder, the build will not fail gracefully. It treats --mount as regular command arguments passed to /bin/sh.

You will see an error like this:

text
/bin/sh: npm: not found
The command '/bin/sh -c --mount=type=secret,id=npmrc,target=/app/.npmrc npm ci' returned a non-zero code: 127

Or the builder ignores the mount flags entirely and tries to execute the flags as bash code.

To avoid this ambiguity across mixed development environments and CI runners, always place this exact line as the absolute first line of your Dockerfile:

dockerfile
# syntax=docker/dockerfile:1

This parser directive instructs the Docker client to use the official container build features that support secret mounts, regardless of the default engine settings on the host machine.

More in Bash