QA
Intermediate LevelDocker & Deployment

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:

1
Secret is passed to build via --secret id=mysecret,src=./my-secret-file or environment variable.
2
During the specific RUN command, BuildKit mounts the secret as a tmpfs file.
3
After the RUN completes, the mount is removed — not committed to any layer.

Code Implementation Example

dockerfile
# 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 build
💡BuildKit --mount=type=secret mounts the token only during execution — never committed to image layers.
🎯 Interview Key Takeaway

Always use BuildKit --mount=type=secret for API tokens and SSH keys in Dockerfiles. ARG/ENV-injected secrets are permanently recoverable from docker history.

#BuildKit#Secret Mounts#Security#API Tokens#Build Security#Intermediate
Back to all Docker & Deployment Questions→

More Docker & Deployment Interview Questions

Beginner LevelDocker & Deployment

How do Docker Multi-Stage Builds minimize image size and improve security?

Beginner LevelDocker & Deployment

What is the difference between a Docker Container and a Virtual Machine (VM)?

Beginner LevelDocker & Deployment

What is the difference between a Docker Image and a Docker Container?