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.)
More on Write-a-Dockerfile tasks
Write a production Dockerfile for a Node.js API using a multi-stage build.IntermediateWrite a Dockerfile for a Python Flask app that runs with gunicorn as a non-root user.BeginnerWrite a Dockerfile for a Go service that produces a tiny image (under 20 MB).IntermediateWrite a multi-stage Dockerfile for a Java Spring Boot app built with Maven.IntermediateWrite a Dockerfile for a static React site served by Nginx.BeginnerThis Dockerfile rebuilds dependencies on every code change. Fix it.Beginner