How do BuildKit secret mounts (RUN --mount=type=secret) prevent build-time API token leaks?
❓ Interview Prompt: Explain how BuildKit secret mounts expose secrets to RUN commands without writing them into any image layer.
A common mistake is passing API tokens or SSH keys as ARG or ENV variables during docker build. Even if you unset them, they remain permanently visible in docker history for every image layer.
The Problem with ARG/ENV Secrets:
```dockerfile
ARG NPM_TOKEN # ← visible in docker history --no-trunc
RUN npm install # token in environment during this layer
```
Anyone with access to the image can run docker history myimage and retrieve the token.
BuildKit Secret Mounts — Zero Layer Exposure:
BuildKit's RUN --mount=type=secret,id=mysecret exposes the secret as a temporary file at `/run/secrets/mysecret` — accessible only during that specific RUN instruction's execution. It is never written into any image layer.
How It Works:
--secret id=mysecret,src=./my-secret-file or environment variable.RUN command, BuildKit mounts the secret as a tmpfs file.RUN completes, the mount is removed — not committed to any layer.Code Implementation Example
# syntax=docker/dockerfile:1.5
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
# Secret mount — NPM_TOKEN only exists during THIS RUN instruction
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/:_authToken
# Token is GONE from image after this RUN — not in any layer!
COPY . .
RUN npm run buildAlways use BuildKit --mount=type=secret for API tokens and SSH keys in Dockerfiles. ARG/ENV-injected secrets are permanently recoverable from docker history.