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.
5.1 Image Size
Section titled “5.1 Image Size”Why Image Size Matters
Section titled “Why Image Size Matters”- 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, orpython) they need to exploit the system further.
Large vs Small Images
Section titled “Large vs Small Images”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.
Minimal Base Images
Section titled “Minimal Base Images”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.
5.2 Multi-Stage Builds
Section titled “5.2 Multi-Stage Builds”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.
Builder Stage
Section titled “Builder Stage”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.
Runtime Stage
Section titled “Runtime Stage”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.
COPY --from
Section titled “COPY --from”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.
Example Multi-Stage Build
Section titled “Example Multi-Stage Build”# Stage 1: BuilderFROM golang:1.20 AS builderWORKDIR /appCOPY . .# Compile the Go applicationRUN go build -o myapp main.go
# Stage 2: RuntimeFROM alpine:latestWORKDIR /app# Only copy the compiled binary from the 'builder' stage!COPY --from=builder /app/myapp .CMD ["./myapp"]5.3 Base Images
Section titled “5.3 Base Images”Choosing the correct FROM image dictates the starting size and security posture of your container.
Ubuntu / Debian
Section titled “Ubuntu / Debian”- 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.
Slim Images
Section titled “Slim Images”- 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).
Alpine Linux
Section titled “Alpine Linux”- Size: Tiny (~5MB).
- Use Case: The most popular minimal base image. It replaces standard GNU tools with BusyBox and uses
musl libcinstead ofglibc. Highly recommended for production. - Warning: Because it uses
muslinstead ofglibc, some pre-compiled binaries (like certain Python C-extensions or Node modules) may require manual compilation inside Alpine.
Distroless Images
Section titled “Distroless Images”- 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 likelsorgrep. They provide the absolute highest level of security because it is nearly impossible for an attacker to run commands inside them.
5.4 Optimization Techniques
Section titled “5.4 Optimization Techniques”Beyond multi-stage builds and base image selection, follow these techniques to shave off every possible megabyte.
Reduce Layers
Section titled “Reduce Layers”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.
Combine Commands Where Appropriate
Section titled “Combine Commands Where Appropriate”Instead of writing multiple RUN instructions, chain them together using &&.
Bad (Creates 3 layers):
RUN apt-get updateRUN apt-get install -y curlRUN 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/*Remove Package Caches
Section titled “Remove Package Caches”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/UbuntuRUN apt-get install -y nginx && rm -rf /var/lib/apt/lists/*
# For AlpineRUN apk add --no-cache curlUse .dockerignore
Section titled “Use .dockerignore”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.
Minimal Runtime Dependencies
Section titled “Minimal Runtime Dependencies”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.
# Example: Only install production dependenciesnpm install --production