✦ For everyone, free.

Practical knowledge for real and everyday life

Home

11.1.3.4 BuildKit Secret Use

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

BuildKit secret use provides the correct, purpose-built mechanism for making a sensitive value available to a specific build step without that value ever being written into any persisted image layer, solving the secret leakage problem that ordinary build arguments and environment variables cannot avoid.

The Basic Mechanism

A secret is supplied at build time and mounted into a specific instruction, available only for that instruction's execution.

RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) npm install
docker build --secret id=npm_token,src=./npm_token.txt -t myapp .

The secret's content is available at /run/secrets/npm_token only during this specific RUN instruction's execution, never persisted into the resulting layer.

Verifying the Secret Doesn't Appear in the Final Image

Confirming the secret genuinely isn't present in the built image validates this mechanism worked as intended.

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

The second command should fail, confirming the secret file doesn't exist in the final image at all, having only ever existed transiently during the specific build instruction that needed it.

Using an Environment Variable Source for the Secret

Rather than a file, a secret's value can also be sourced from an environment variable available at build time.

export NPM_TOKEN=secret123
docker build --secret id=npm_token,env=NPM_TOKEN -t myapp .
Why This Mechanism Specifically Requires BuildKit

This capability depends on BuildKit, Docker's modern build engine — ensuring BuildKit is actually enabled is a prerequisite for using this secret mounting syntax at all.

DOCKER_BUILDKIT=1 docker build --secret id=npm_token,src=./npm_token.txt -t myapp .
Why BuildKit Secret Use Matters

This is the only reliable, purpose-built mechanism for using a genuinely sensitive value during an image build without permanently embedding it into the resulting image, making it the correct approach whenever a build step genuinely needs access to a secret like a private package registry token or a build-time API credential.