🔑 npm install Needs Token. But Token Shouldn’t Be in Image.
Build-time secrets (npm tokens, SSH keys) often leak into layers. Docker BuildKit secrets mount secrets at build time, never stored.
📝 Dockerfile with Secrets
# syntax=docker/dockerfile:1.4
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
# Secret mount (not stored in layer)
RUN --mount=type=secret,id=npmrc \
cp /run/secrets/npmrc .npmrc && \
npm ci
COPY . .
RUN npm run build
FROM node:18-alpine
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/server.js"]
🔧 Build with Secret
# Create secret file
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
# Build with secret
DOCKER_BUILDKIT=1 docker build \
--secret id=npmrc,src=.npmrc \
-t myapp .
# Clean up secret after build
rm .npmrc
# Multi-secret example
RUN --mount=type=secret,id=github_token \
--mount=type=secret,id=aws_key \
./deploy.sh
💡 Why This Matters
- Traditional ARG/ENV leaves secrets in image layers (docker history)
- Secrets mount only exists during RUN command, not in final image
- Perfect for npm tokens, SSH keys, API keys
- Requires BuildKit (DOCKER_BUILDKIT=1)
“NPM token was in my image. Anyone with docker history could see it. Build secrets fixed it. Token used only during build, not stored. Security win.”
