In this lesson, you will learn how individual Dockerfile instructions act as triggers that commit changes to your image’s filesystem as distinct layers.
The Layered Anatomy of an Image
Think of a Docker image like an onion. Every time you write a specific instruction in your Dockerfile, Docker creates a new, read-only layer on top of the existing one. Once a layer is created, it is immutable—it cannot be changed, only replaced by a new layer stacked on top.
Instructions That Create Layers
Not all commands are created equal. The instructions that modify the filesystem are the ones responsible for adding these layers:
RUN: Executes a command (likeapt-get install) and saves the resulting filesystem changes.COPY: Copies files from your local machine into the image.ADD: Similar toCOPY, but can also extract archives.
For example, consider this snippet:
FROM ubuntu:22.04
RUN apt-get update
RUN apt-get install -y python3
COPY app.py /app/
In this case, Docker builds the image in stages. First, the base ubuntu image is pulled. Then, RUN apt-get update creates a layer. Next, RUN apt-get install -y python3 creates another layer on top of that. Finally, COPY app.py /app/ adds the final layer.
Why This Matters for Size
Because each layer captures the "diff" (the difference between the previous state and the new state), every RUN command adds to the total image size. If you install a large package in one RUN command and delete it in another RUN command, the package remains inside the first layer forever, bloating your final image size.
To keep images small, developers often combine commands using the && operator:
# This creates only one layer for both operations
RUN apt-get update && apt-get install -y python3 && rm -rf /var/lib/apt/lists/*
By chaining these commands, you ensure that temporary cache files created during the update or installation are discarded before the layer is finalized, preventing them from consuming unnecessary space in your final image.
Key Takeaway: Only RUN, COPY, and ADD instructions create new filesystem layers, so grouping commands into a single instruction is the most effective way to minimize your image size.