BudiBadu Logo
Samplebadu

Dockerfile by Example: Image Optimization Techniques

Docker Engine 20.10+

Optimizing images reduces storage costs and speeds up deployments. This sample code illustrates techniques like chaining commands and cleaning caches.

Code

FROM debian:bullseye-slim

# Bad Practice (Creates 3 layers):
# RUN apt-get update
# RUN apt-get install -y curl
# RUN rm -rf /var/lib/apt/lists/*

# Good Practice (Creates 1 layer):
RUN apt-get update && apt-get install -y \
    curl \
    vim \
    git \
    && rm -rf /var/lib/apt/lists/*

# Use .dockerignore to exclude files
COPY . .

# Use multi-stage builds (see previous example)
# ...

Explanation

Docker image optimization focuses on reducing the final image size and the number of layers. Each RUN, COPY, and ADD instruction creates a new layer. If you install a package in one layer and remove it in the next, the file is deleted from the final filesystem view, but the data remains in the previous layer, bloating the image. Therefore, it is crucial to perform installation and cleanup in a single RUN instruction.

Optimization strategies include:

  • Chain commands with && to consolidate operations into a single layer
  • Clean up package manager caches (apt/apk) immediately after installation
  • Use .dockerignore to prevent copying unnecessary build artifacts
  • Choose minimal base images like alpine or slim variants

Using "slim" or "alpine" base images is the most effective way to start small. Debian-slim images lack man pages and other documentation, while Alpine images use a completely different, lightweight C library (musl). Combining these base images with multi-stage builds and disciplined layer management results in efficient, production-ready containers that are fast to pull and deploy.

Code Breakdown

9
RUN ... && ... chains commands to form a single filesystem layer.
13
rm -rf ... cleans up temporary data before the layer is committed.
1
debian:bullseye-slim is a smaller variant of the standard Debian image.
3-6
Comments illustrate the "Bad Practice" of creating multiple redundant layers.