3 Hours

6. Optimizing Docker Images for Size and Speed

Optimization

Reducing Image Size by 90% (or More)

Large images are slow to build, slow to push, slow to pull, and contain more vulnerabilities. This module teaches advanced optimization techniques that professionals use to reduce image sizes from gigabytes to megabytes.

Why Image Size Matters

Every megabyte of your image size has real costs. In CI/CD pipelines, large images mean slower builds and slower deployments, which means slower feedback loops for developers. In production, large images increase pull times during autoscaling events — when your application needs to scale up to handle traffic, every second your new instances spend pulling the image is a second they are not serving requests. In Kubernetes environments, images are pulled to every node where a pod runs, so large images increase cluster resource usage. Large images also contain more software, which means more potential vulnerabilities. The difference between a 1.2GB image and a 50MB image is not just disk space — it's deployment speed, security posture, and operational efficiency.

Base Image Selection: The Single Biggest Impact

The base image you choose determines the floor of your image size — you cannot go smaller than the base image plus your application. `ubuntu:22.04` is about 77MB. `debian:bookworm-slim` is about 80MB. `alpine:3.19` is about 7MB — ten times smaller than Ubuntu. For interpreted languages like Python and Node.js, using the Alpine variant of the official images gives you a dramatically smaller starting point. For compiled languages like Go and Rust, you can use `scratch` — literally zero bytes — because you can compile a static binary that has no dependencies. Before you optimize anything else, ensure you are using the smallest base image that works for your application. Some software may have compatibility issues with Alpine's musl libc (vs glibc). If your application requires glibc, use a `-slim` variant instead of `-alpine` — still smaller than full images.

Text
# Full images (bad for most apps)
FROM ubuntu:22.04        # 77MB base
FROM node:20             # 990MB base
FROM python:3.12         # 950MB base

# Slim images (good for glibc compatibility)
FROM debian:bookworm-slim   # 80MB base
FROM node:20-slim           # 200MB base
FROM python:3.12-slim       # 150MB base

# Alpine images (best for size, musl libc)
FROM alpine:3.19            # 7MB base
FROM node:20-alpine         # 170MB base
FROM python:3.12-alpine     # 120MB base

# Scratch (zero bytes — for static binaries)
FROM scratch                 # 0MB base

Cleaning Up Package Manager Caches

Package managers like `apt`, `apk`, `yum`, `pip`, and `npm` store cache files to speed up future installs. These caches are useless in a Docker image because the image will never run another install — the cache only wastes space. You MUST clean up these caches in the same RUN instruction that installed the packages. For `apt` (Debian/Ubuntu), this means running `rm -rf /var/lib/apt/lists/*` after your `apt-get install`. For `apk` (Alpine), use the `--no-cache` flag which prevents caching entirely. For `pip`, use `--no-cache-dir`. For `npm`, the cache is stored in `~/.npm`, so delete it after `npm install`. Here is the pattern: install packages, then immediately clean up, all in one RUN instruction. If you split cleanup into a separate RUN, the cache files would still exist in the previous layer and contribute to the final image size.

Text
# Good — apt cleanup in same layer
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        curl \
        git \
    && rm -rf /var/lib/apt/lists/*

# Good — Alpine's --no-cache flag
RUN apk add --no-cache curl git

# Good — pip cleanup
RUN pip install --no-cache-dir -r requirements.txt

# Good — npm cleanup
RUN npm ci && npm cache clean --force

# Bad — cleanup in separate layer
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*  # Too late — the lists are already in layer 1!

Minimizing Layer Count and Size

Every instruction creates a new layer. While layers have benefits (caching, sharing), too many layers can increase image size because each layer stores its own filesystem changes. The solution is not to cram everything into one `RUN` instruction (that would hurt cache efficiency), but to be intentional. Group related operations into single `RUN` instructions. For example, all package installations can go in one `RUN`. All source code copying goes in one `COPY`. This reduces overhead while preserving logical cache boundaries. Also, order your layers so that frequently changing operations come last — this maximizes cache reuse without increasing final image size.

Multi-Stage Builds: The Ultimate Optimization

Multi-stage builds are covered in depth in the next module, but the core idea is that you use one image to build your application (with compilers, package managers, source code) and a different, much smaller image to run it. The build image can be gigabytes — it doesn't matter because it is discarded. The final runtime image contains only the compiled artifacts and runtime dependencies. For Go applications, this means you can go from a 1.2GB build image to a 12MB scratch-based image — a 99% reduction. For Node.js applications, you can go from a 900MB image (including TypeScript compiler and source code) to a 150MB image (only compiled JavaScript and production dependencies). Multi-stage builds are so powerful that every production Dockerfile for compiled languages should use them.

Text
# Before: 1.2GB image
FROM node:20
COPY . .
RUN npm install
RUN npm run build
CMD ["node", "dist/server.js"]

# After: 180MB image (using multi-stage)
FROM node:20 AS builder
WORKDIR /build
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-slim
WORKDIR /app
COPY --from=builder /build/dist ./dist
COPY --from=builder /build/node_modules ./node_modules
CMD ["node", "dist/server.js"]

Knowledge Check

Ready to test your understanding of 6. Optimizing Docker Images for Size and Speed?

Back