How do you reduce Docker image size? Walk through your optimization strategy.
Image size directly affects pull times and attack surface. Key strategies:
- Use minimal base images:
alpineordistrolessinstead ofubuntu. - Multi-stage builds: Build in a full image, copy only the binary/artifact to a slim final image.
- Combine RUN commands: Each RUN creates a layer. Chain commands with
&&and clean up in the same layer. - Use .dockerignore: Exclude
node_modules,.git, test files from the build context.
# Multi-stage example
FROM node:20 AS builder
WORKDIR /app
COPY . .
RUN npm ci && npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/index.js"]