Multi-Stage Build — multiple build stages in a single Dockerfile for smaller final images.
1# Stage 1: Build2FROM node:20-alpine AS builder3WORKDIR /app4COPY package*.json ./5RUN npm ci --only=production6COPY . .7RUN npm run build89# Stage 2: Test10FROM node:20-alpine AS test11WORKDIR /app12COPY --from=builder /app .13RUN npm ci14RUN npm run test1516# Stage 3: Production17FROM node:20-alpine AS production18RUN addgroup -S appgroup && adduser -S appuser -G appgroup19WORKDIR /app20COPY --from=builder /app/dist ./dist21COPY --from=builder /app/node_modules ./node_modules22COPY package*.json ./23USER appuser24EXPOSE 300025HEALTHCHECK --interval=30s --timeout=3s \26 CMD wget -qO- http://localhost:3000/health || exit 127CMD ["node", "dist/main.js"]2829# Stage 4: Debug (only used with --target debug)30FROM production AS debug31USER root32RUN apk add --no-cache curl bash33CMD ["sh", "-c", "node dist/main.js & sleep infinity"]
1# Build specific stage2docker build --target production -t myapp:latest .3docker build --target debug -t myapp:debug .45# Copy from specific stage6COPY --from=builder /app/dist ./dist7COPY --from=0 /app/dist ./dist # by index
Benefits: