✦ For everyone, free.

Practical knowledge for real and everyday life

Home

5.2.1.4 BuildKit Secret Mounts

A focused guide to BuildKit Secret Mounts, connecting core concepts with practical Docker and container operations.

BuildKit secret mounts allow a Dockerfile to access sensitive values — API tokens, private registry credentials — during a single RUN instruction's execution, without those values ever being written into the resulting image's layers or persisted anywhere beyond that instruction's runtime.

Why This Solves a Real Problem

Before secret mounts, supplying a credential to a build step typically meant either passing it as a build argument (which can leak into image history) or hardcoding it temporarily and trying to remove it afterward (which doesn't actually remove it from earlier layers). Secret mounts provide a way to use a secret without it ever becoming part of any layer at all.

RUN --mount=type=secret,id=npm_token \
    npm config set //registry.npmjs.org/:_authToken=$(cat /run/secrets/npm_token) \
    && npm install
docker build --secret id=npm_token,src=./npm_token.txt -t myapp .

The secret file's contents are available at /run/secrets/npm_token only during this specific RUN instruction's execution, and never appear in the resulting image's layer history.

Verifying the Secret Doesn't Leak Into the Image

Confirming that a secret used this way truly does not appear anywhere in the final image provides direct evidence the mechanism is working as intended.

docker history myapp:1.0
docker run --rm myapp:1.0 cat /run/secrets/npm_token

The second command should fail, since the secret mount only exists during the specific build instruction that requested it, not in the resulting running container.

Using Secrets From Environment Variables

A secret can also be supplied directly from an environment variable rather than a file, which is convenient in CI pipelines where secrets are commonly already available as environment variables.

docker build --secret id=npm_token,env=NPM_TOKEN -t myapp .
Why Secret Mounts Matter

Secret mounts directly solve a previously awkward and risky problem — needing a credential during a build step without permanently baking it into the resulting image — making it possible to build images requiring authenticated access to private resources without compromising the resulting artifact's safety.