patterndockerMajor
BuildKit secrets mount credentials without baking them into image layers
Viewed 0 times
Requires BuildKit (Docker 18.09+), default in Docker 23+
BuildKitsecretsmount type secretnpm tokensshcredentialsdocker history
Problem
Build steps need access to credentials (npm auth tokens, SSH keys, API keys) but passing them as ARG or ENV bakes them into the image history where they can be recovered with
docker history.Solution
Use BuildKit
--mount=type=secret to mount secrets only during the specific RUN that needs them:# syntax=docker/dockerfile:1
FROM node:20-alpine
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN=$(cat /run/secrets/npm_token) \
npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN \
&& npm ci \
&& npm config delete //registry.npmjs.org/:_authTokendocker build --secret id=npm_token,src=$HOME/.npmrc .Why
BuildKit secret mounts are never written to the union filesystem or any image layer. The secret is accessible only in the RUN step's execution environment as a tmpfs mount at /run/secrets/.
Gotchas
- Requires BuildKit (DOCKER_BUILDKIT=1 or Docker 23+ where it's the default)
- The
# syntax=docker/dockerfile:1comment at the top enables the Dockerfile frontend that supports secrets - SSH agent forwarding uses
--mount=type=ssh— useful for private git repos during build - Secrets are mounted read-only at /run/secrets/<id> by default
Code Snippets
BuildKit SSH and secret mounts
# syntax=docker/dockerfile:1
FROM python:3.12-slim
# Mount SSH agent for private git dependencies
RUN --mount=type=ssh \
pip install git+ssh://git@github.com/myorg/private-lib.git
# Mount a secret file
RUN --mount=type=secret,id=pip_conf,dst=/etc/pip.conf \
pip install -r requirements.txtBuild commands with secrets and SSH forwarding
# Enable SSH agent forwarding during build
eval $(ssh-agent)
ssh-add ~/.ssh/id_ed25519
docker build --ssh default .
# Pass a secret from a file
docker build --secret id=pip_conf,src=$HOME/.pip/pip.conf .Context
Builds that need credentials to access private package registries or git repos
Revisions (0)
No revisions yet.