How to Reduce Docker Image Size – From Kitchen to Tiffin Box 🍱

β€’

The Tiffin Box Analogy 🍱


1. The “Big Win”: Multi-Stage Builds

❌ The “Single-Stage” Mistake

FROM node:18
WORKDIR /app
COPY . .
RUN npm install && npm run build
CMD ["node", "dist/index.js"] 
# Result: ~900MB (This is carrying the stove in your tiffin box!)

βœ… The Multi-Stage Best Practice

# Stage 1: The Kitchen (Build)
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build

# Stage 2: The Tiffin Box (Runtime)
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/index.js"]
# Result: ~120MB

2. Choose Your Base Image Wisely

Base ImageTypical SizeNote
node:18~900 MBFull Debian-based image.
node:18-slim~200 MBMinimal Debian, no extra utilities.
node:18-alpine~120 MBUses Alpine Linux (very small, but uses musl).
distroless~50 MBNo shell, no package manager. The ultimate “tiffin.”

3. Clean Your Layers (and Do It in One Go)

  • Bad: Three layers, file remains in history.DockerfileRUN apt-get update RUN apt-get install -y curl RUN rm -rf /var/lib/apt/lists/*
  • Good: One layer, file is deleted before the layer is finalized.DockerfileRUN apt-get update && apt-get install -y \ --no-install-recommends curl \ && rm -rf /var/lib/apt/lists/* (Note: Using --no-install-recommends prevents APT from installing “suggested” packages you don’t need.)

4. Use .dockerignore

.git
node_modules
*.log
Dockerfile
.env

5. Advanced Power Moves

  • Audit with dive: Use the dive tool to inspect your image layer-by-layer. It will show you exactly which files are taking up space.
  • Static Binaries: If you use Go or Rust, compile your app into a single static binary and use a scratch (empty) base image. This can result in images under 10MB.
  • Experimental Squashing: Use docker build --squash to collapse all your layers into one, removing all historical “ghost” data.

Summary Checklist

  • [ ] Is it a Multi-Stage build?
  • [ ] Did I use an Alpine or Slim base?
  • [ ] Are my RUN commands chained (&&)?
  • [ ] Is there a .dockerignore file?
  • [ ] Did I use –no-install-recommends?

β€’

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *