tezvyn:

Pass build-time secrets securely with BuildKit

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

secure build secret handling.

OUTLINE

use BuildKit RUN --mount=type=secret (or type=ssh) so the secret is mounted only during that step and never written to a layer; pass it with --secret at build time.

WHAT THIS TESTS It checks whether you know that build args and env vars leak into image metadata, and can use BuildKit's secret mounts to avoid persisting credentials.

A GOOD ANSWER COVERS The wrong approaches leak: ARG and ENV values are visible via docker history and can be inspected, and COPYing a key file leaves it in a layer even if you delete it later, because earlier layers persist. The modern BuildKit approach mounts secrets only for the duration of a single RUN. You write RUN --mount=type=secret,id=npmtoken sh -c 'NPM_TOKEN=$(cat /run/secrets/npmtoken) npm ci', and invoke docker build --secret id=npmtoken,src=./npm_token.txt. The file is mounted into a tmpfs at /run/secrets during that step and never becomes part of any image layer. For SSH-based private repos, RUN --mount=type=ssh forwards the host SSH agent so the key itself never enters the build. BuildKit is the default builder in modern Docker.

COMMON WRONG ANSWERS Using ARG NPM_TOKEN, which shows up in history. Setting ENV with the secret. COPYing a key then RUN rm, not realizing the prior layer still contains it. Believing multi-stage alone hides secrets used in an early stage's history.

LIKELY FOLLOW-UPS Why does deleting a file in a later layer not remove it? How does --mount=type=ssh differ from type=secret? How are runtime secrets handled differently from build-time ones?

ONE CONCRETE EXAMPLE Installing private npm packages: the Dockerfile uses RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, and the build runs with docker build --secret id=npmrc,src=$HOME/.npmrc -t app . The registry credentials are present only while npm ci runs; docker history on the final image reveals nothing, and no layer contains the token.

Read the original → docs.docker.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.