Interview Prep/Real-World Interview/Write-a-Dockerfile tasks

Write a Dockerfile that uses a build secret (e.g. a private npm token) without leaking it into image layers.

AdvancedHands-onWrite-a-Dockerfile tasks
Answer
# syntax=docker/dockerfile:1
FROM node:22-alpine
WORKDIR /app
COPY package*.json .npmrc ./
RUN --mount=type=secret,id=npm_token,env=NPM_TOKEN \
    npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]

.npmrc contains //registry.npmjs.org/:_authToken=${NPM_TOKEN}. Build with:

docker build --secret id=npm_token,env=NPM_TOKEN -t app .

Key trick → BuildKit secret mounts exist only for that single RUN step and are never written to a layer. ARG/ENV values stay visible in docker history. (The env= form of the mount needs a recent Dockerfile frontend; the older form mounts the secret at /run/secrets/npm_token instead.)

All Real-World Interview questions Roadmap: Interview readiness

More on Write-a-Dockerfile tasks