How do you reduce Docker image size?
Answer
Smaller images are faster to build, push, pull, and have a smaller attack surface. Strategies: (1) Use minimal base images: prefer alpine variants (node:20-alpine ~50MB vs node:20 ~350MB); for compiled languages, use scratch (empty) or distroless images; (2) Multi-stage builds: separate build tools from runtime — only copy the built artifacts to the final stage; (3) Combine RUN instructions: each RUN creates a layer — combine commands with && to reduce layers and clean up in the same step: RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/* — the cleanup is in the same layer and actually reduces size; (4) Remove caches and temp files: for apt: rm -rf /var/lib/apt/lists/*; for npm: npm ci --only=production or npm cache clean --force; (5) Use .dockerignore: exclude node_modules, .git, tests, docs; (6) Avoid unnecessary packages: don't install debugging tools in production images; (7) Use COPY instead of ADD; (8) Pin specific versions not :latest; (9) Analyze with dive tool (visualizes layers and wasted space) or docker image history myimage.
Previous
What is the difference between EXPOSE and port publishing in Docker?
Next
What is the USER instruction in Dockerfile?