Docker lab/version note: use supported Linux-container tools and patched images. Check version compatibility before running the examples. Docker, Swarm and platform-specific deployment steps were not tested live.
What this guide covers
BuildKit can mount a registry credential during one build instruction without copying the credential file into the image. A dependency cache can speed downloads, but it does not replace a lockfile.
Before you start
Use BuildKit or Buildx, a Node.js application with package.json and package-lock.json, and a protected npm configuration file outside the repository. The example starts server.mjs and has no compilation step. Add .npmrc, secrets, environment files and node_modules to .dockerignore.
Step 1: Create the Dockerfile
Save this as Dockerfile:
# syntax=docker/dockerfile:1
FROM node:24-bookworm-slim AS dependencies
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,id=npm-downloads,target=/root/.npm \
--mount=type=secret,id=npmrc,target=/run/secrets/npmrc,required=true \
npm ci --omit=dev --userconfig=/run/secrets/npmrc
FROM node:24-bookworm-slim AS runtime
ENV NODE_ENV=production PORT=3000
WORKDIR /app
COPY --from=dependencies --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node package.json server.mjs ./
USER node
EXPOSE 3000
CMD ["node", "server.mjs"]
The npm configuration is mounted only for the install instruction. The final stage receives installed dependencies, not the secret file. However, package install scripts can read the mounted secret, so use trusted dependencies and a limited registry token.
Step 2: Supply the secret at build time
Run:
read -r -p 'Absolute path to protected npm configuration: ' NPMRC_PATH
test -f "$NPMRC_PATH"
docker buildx build --secret id=npmrc,src="$NPMRC_PATH" \
--load --tag node-secret-lab:1.0 .
docker image inspect node-secret-lab:1.0 --format '{{.Config.User}} {{json .Config.Cmd}}'
docker image history --no-trunc node-secret-lab:1.0
Enter the protected file’s absolute path. Do not use a Docker build argument or COPY to pass the token. Do not print the file contents in build logs.
Step 3: Check rebuild behavior
Changing a secret does not necessarily invalidate a cached build instruction. If a credential rotation must force installation again, explicitly invalidate the relevant cache or run a reviewed no-cache build. Keep caches separate between trusted and untrusted builders.
Step 4: Test the runtime
Start the built image and check the actual application. If the project needs TypeScript or another build tool, install build dependencies and compile in a separate stage before creating the production-only runtime.
Check the result
The build should authenticate without committing credentials, and the final image should run without the registry secret. Review logs, copied files and package behavior rather than assuming a secret mount prevents every possible leak.
Conversation
0 commentsNo comments yet. Start the conversation below.