Skip to content

05. Image Optimization

In the world of containerization, smaller is always better. Optimizing your Docker images is critical for speeding up deployments, reducing storage costs, and minimizing your security attack surface.

  • Faster Deployments: Smaller images pull across networks faster, allowing containers to start and scale rapidly.
  • Lower Costs: Storing massive images in registries (like AWS ECR) and transferring them across nodes incurs high bandwidth and storage costs.
  • Security: A smaller image contains fewer libraries and tools, dramatically reducing the attack surface. If an attacker breaches the container, a minimal image lacks the tools (like curl, bash, or python) they need to exploit the system further.

A typical Node.js or Python application built on a standard ubuntu base image can easily exceed 1GB. By optimizing the build process and selecting the right base image, that exact same application can be reduced to 50MB.

Using minimal base images is the foundation of optimization. Instead of starting with a full operating system, you start with the absolute bare minimum required to execute your code.

Multi-stage builds are the single most powerful feature for Docker image optimization. They allow you to separate the environment used to build the application from the environment used to run the application.

In a compiled language (like Go, Rust, or TypeScript), you need compilers, SDKs, and source code to build the binary. These tools take up massive amounts of space. The builder stage uses a heavy image to compile the application.

Once the application is compiled into a binary, it no longer needs the compiler or source code. The runtime stage starts completely fresh with a tiny base image.

This instruction bridges the gap. It copies only the compiled artifact from the heavy builder stage into the tiny runtime stage, leaving all the heavy build dependencies behind.

# Stage 1: Builder
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .
# Compile the Go application
RUN go build -o myapp main.go
# Stage 2: Runtime
FROM alpine:latest
WORKDIR /app
# Only copy the compiled binary from the 'builder' stage!
COPY --from=builder /app/myapp .
CMD ["./myapp"]

Choosing the correct FROM image dictates the starting size and security posture of your container.

  • Size: Very Large (~70MB to 120MB+ compressed).
  • Use Case: Good for development and debugging because they contain full package managers (apt) and standard GNU utilities. Rarely recommended for final production workloads unless specifically required by complex dependencies.
  • Size: Medium (~30MB to 50MB).
  • Use Case: A stripped-down version of Debian/Ubuntu. Things like man pages, documentation, and non-essential tools are deleted. (e.g., node:18-slim, python:3.10-slim).
  • Size: Tiny (~5MB).
  • Use Case: The most popular minimal base image. It replaces standard GNU tools with BusyBox and uses musl libc instead of glibc. Highly recommended for production.
  • Warning: Because it uses musl instead of glibc, some pre-compiled binaries (like certain Python C-extensions or Node modules) may require manual compilation inside Alpine.
  • Size: Microscopic.
  • Use Case: Created by Google, distroless images contain only your application and its runtime dependencies. They do not even contain a package manager, a shell (/bin/sh), or basic utilities like ls or grep. They provide the absolute highest level of security because it is nearly impossible for an attacker to run commands inside them.

Beyond multi-stage builds and base image selection, follow these techniques to shave off every possible megabyte.

Every RUN, COPY, and ADD command creates a new read-only layer. While modern BuildKit handles this better, it is still a best practice to minimize unnecessary layers.

Instead of writing multiple RUN instructions, chain them together using &&. Bad (Creates 3 layers):

RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*

Good (Creates 1 layer):

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

Always delete the cache generated by package managers in the exact same RUN step where you installed the packages. If you delete the cache in a subsequent RUN layer, the cache is still permanently baked into the previous layer!

# For Debian/Ubuntu
RUN apt-get install -y nginx && rm -rf /var/lib/apt/lists/*
# For Alpine
RUN apk add --no-cache curl

As discussed previously, prevent massive files (like .git/, local node_modules/, or build logs) from ever entering the Docker build context. This speeds up the build process and prevents accidental bloat.

Audit your application. If a library is only required for testing (e.g., devDependencies in Node.js), do not install it in the final production image.

Terminal window
# Example: Only install production dependencies
npm install --production