The before picture
FROM node:20
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
CMD ["node", "dist/main.js"]
This copies everything — devDependencies, test files, source code — into the final image. The node:20 base alone is 900MB.
The after picture
# Stage 1: Install and build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
# Stage 2: Production image
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/main.js"]
Why this works
- Alpine base: 50MB instead of 900MB
- No devDependencies in production: The builder stage installs everything, but only
distandnode_modulesare copied to the final image - Layer caching:
package.jsonis copied before source code, so dependency installation is cached unless lockfile changes
Prune devDependencies properly
For an even smaller image, prune after build:
RUN pnpm prune --prod
This dropped our node_modules from 380MB to 95MB.
Security: run as non-root
The USER node line is not optional. Running as root inside a container means a compromised process has root access to the container filesystem. Alpine's node image ships with a node user — use it.
Results
- Image size: 1.2GB to 140MB
- Build time with cache: 45s to 12s
- Deploy pull time: 3 min to 20s
- CVE scan findings: reduced by 80 percent (fewer packages = fewer vulnerabilities)
