Course contentsShow
← Cloud and Infrastructure
Lesson 1022 of 2,98920. Docker in DepthFree lesson

Minimizing Image Size

Techniques to reduce final image size: removing unnecessary files and using slim base images.

Minimizing Image Size

You'll learn: how to shrink your Docker images by removing waste and choosing leaner base images.

Why Image Size Matters

Large container images slow down deployments, consume more storage, increase network transfer time, and expand your attack surface. Every unnecessary file is baggage your container carries through its entire lifecycle—from build to registry to production.

Core Techniques

1. Remove Unnecessary Files

After running commands that create temporary artifacts (package manager caches, build artifacts, logs), clean them up in the same RUN instruction:

RUN apt-get update && \
    apt-get install -y python3 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

Deleting files in a later layer doesn't reduce size—the bloat is already baked into an earlier layer.

2. Use Slim Base Images

Instead of full OS images like ubuntu:latest (~77MB), choose minimal variants:

  • ubuntu:22.04-slim (~28MB)
  • python:3.11-slim (slimmed Python with essentials)
  • alpine:latest (~5MB, uses musl libc)
  • Distroless images (runtime-only, no shell or package manager)
# Before: 1.1GB
FROM node:18
COPY . .
RUN npm install

# After: 180MB
FROM node:18-alpine
COPY . .
RUN npm install

Multi-Stage Builds Synergy

Combine these techniques with multi-stage builds: compile in a full image, copy only the final binary to a slim runtime image.

Analogy

Think of packing a suitcase. Don't pack your entire workshop (full OS)—pack only the screwdriver you need (slim base). And throw away the instruction manuals after assembly (clean temporary files).

Key Takeaway: Minimize image size by deleting temporary files in the same layer where they're created and choosing the smallest base image that meets your runtime needs.