docker multi-stage build — reduce image size
Quick Answer
# Dockerfile — multi-stage example for a Node.js app
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage — only the built output
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/index.js"]
When to use
Your production image is larger than necessary because it contains compilers, dev dependencies, or build tools.
Other causes & fixes
Go — build a tiny static binary
FROM golang:1.22 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o server .
FROM scratch
COPY --from=builder /app/server /server
EXPOSE 8080
ENTRYPOINT ["/server"]
Copy only specific files from a stage
# Name your stages and reference them in COPY --from=
COPY --from=builder /app/dist /app/dist
COPY --from=builder /app/public /app/public
Build a specific stage (for debugging)
# Stop at the builder stage
docker build --target builder -t my-app:debug .
Related