Sub topic 1
How images and layers work
Every size and speed decision in a Dockerfile comes back to one fact: an image is a stack of layers. This chapter explains what a layer is, which instructions create one, how containers use the stack, and why deleting a file in a later step does not make an image smaller. The later chapters on caching, base images and multi-stage builds all build on this model.
Prerequisites
This chapter assumes you can do the following:
- Use a terminal and run commands such as
docker buildanddocker run. - Read a simple Dockerfile and know what
FROM,RUNandCOPYdo at a basic level. - Build a small app in Go, Node.js or Python. The examples here use shell commands only.
You need Docker installed. Output sizes shown below are approximate and will differ on your machine.
What an image contains
A container image is a bundle of three things:
- An ordered list of filesystem layers.
- A configuration, which holds metadata such as the default command, environment variables, exposed ports and the working directory.
- A manifest, which lists the layers and the configuration by their digests.
A digest is a SHA-256 hash of some content, written like sha256:3b1f.... Images are content-addressable, which means each layer and each configuration is identified by the hash of its bytes. Two layers with identical content have the same digest, and changing one byte produces a different digest.
A layer is an archive (a tar file) that records changes to a filesystem: files added, files modified and files deleted. A layer is not a full copy of the filesystem. It is a difference from the layer below it. The layers are read-only once built.
How layers combine into one filesystem
The container runtime does not unpack layers into a single directory by copying. It uses a union filesystem. On most Linux hosts Docker uses overlay2, which is built on the kernel's OverlayFS. A union filesystem presents several directories stacked on top of each other as one merged view.
The rules for the merged view are simple:
- When a path exists in several layers, the topmost layer wins.
- When a path exists only in a lower layer, it shows through.
- When an upper layer records a deletion, the path disappears from the merged view, even though the bytes remain in the lower layer.
When you run a container, Docker adds one thin writable layer on top of the image layers. Writes go there. If a process modifies a file that lives in a lower layer, the runtime first copies that file up into the writable layer and then changes the copy. This is called copy-on-write. The image layers are never modified.
Two consequences follow:
- Many containers started from one image share the same read-only layers on disk. Each container only pays for its own writable layer.
- Data in the writable layer is deleted with the container. Anything that must persist belongs in a volume.
Which instructions create layers
Not every Dockerfile instruction adds data to the image. Instructions that change the filesystem produce a layer with content. Instructions that only set configuration update the image metadata and add no files.
| Instruction | Effect on the image |
|---|---|
| `FROM` | Brings in all layers of the base image |
| `RUN` | Runs a command and stores the filesystem changes as a new layer |
| `COPY`, `ADD` | Stores the copied files as a new layer |
| `WORKDIR` | Sets metadata. It also creates the directory, which adds a small layer if the directory did not exist |
| `ENV`, `ARG`, `LABEL`, `EXPOSE`, `USER`, `CMD`, `ENTRYPOINT` | Metadata only. No file content is added |
docker history lists a row for every instruction, including metadata-only ones, but those rows show a size of 0B.
Layers are cumulative, so the final image size is roughly the sum of its layer sizes. The cost of an instruction is whatever it wrote to the filesystem, and that includes temporary files, package manager caches and downloaded archives.
Deleting a file does not shrink the image
Layers are immutable and each one records differences. A later layer cannot reach into an earlier layer and remove bytes. When a file is deleted in a later layer, that layer stores a marker called a whiteout. In the OCI layer format, a whiteout is an empty file named .wh. followed by the deleted name, for example .wh.big.bin. The union filesystem hides the lower file when it sees the whiteout. The lower layer still holds the data, and it is still downloaded, stored and shipped.
You can see this with two small Dockerfiles. First, a version that creates a 100 MB file in one step and deletes it in the next:
FROM debian:bookworm-slim
RUN dd if=/dev/zero of=/big.bin bs=1M count=100
RUN rm /big.binSecond, a version that does both in a single RUN:
FROM debian:bookworm-slim
RUN dd if=/dev/zero of=/big.bin bs=1M count=100 && rm /big.binSave them as Dockerfile.two and Dockerfile.one, then build both and compare:
docker build -f Dockerfile.two -t layers:two .
docker build -f Dockerfile.one -t layers:one .
docker image ls layers
docker history layers:twoThe two-step image comes out about 100 MB larger than the one-step image. The docker history output for layers:two shows a 100MB row for the dd instruction and a row of about 0B for rm. The file is invisible inside a container, but its bytes are still in the image.
In the single-RUN version, the file is created and removed before the layer is committed. The layer is the filesystem difference at the end of the instruction, and that difference contains no big.bin.
The same rule applies in everyday builds. This pattern keeps the package index out of the final layer:
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*If rm -rf /var/lib/apt/lists/* were a separate RUN, the package lists would remain in the layer created by apt-get update.
Layers are shared and reused
Because layers are identified by digest, Docker can store and transfer each distinct layer once:
- If two images start from the same base image, they share all the base layers on disk.
- When you pull an image, Docker downloads only the layers it does not already have. Layers it has show
Already existsin the pull output. - When you push, the registry skips layers it already stores.
The sharing only works for identical layers at identical positions in the stack. A layer's identity depends on its content, so a changed file in an early layer produces a different layer. The next chapters show how this connects to build caching: Docker also reuses layers between builds of the same Dockerfile, as long as the instruction and its inputs have not changed.
Inspecting the layers of an image
docker history shows the instructions that built an image, with the size each one added. docker image inspect shows the list of layer digests:
docker image inspect layers:two --format '{{json .RootFS.Layers}}'The output is a JSON array of sha256: digests, ordered from the bottom layer to the top. Metadata-only instructions do not appear in this list because they have no layer content. This is why docker history can show more rows than RootFS.Layers has entries.
You may see <missing> in the IMAGE column of docker history. This is normal for layers that were pulled or built by BuildKit. It means no separate local image ID exists for that layer. It does not mean the layer is absent.
Common mistakes
- Expecting
rmin a laterRUNto reclaim space. The data stays in the earlier layer, as shown above. Clean up in the same instruction, or avoid creating the files at all. - Using
COPY . .and then deleting files. The copied files are already in a layer. Exclude them from the copy instead. A later chapter covers.dockerignorefor this. - Treating
chmodorchownafterCOPYas free. Changing the permissions or owner of a large directory in a separateRUNcopies every affected file into a new layer, which doubles that data. UseCOPY --chownorCOPY --chmodwhen possible. - Writing data inside a running container and expecting it in the image. The writable container layer is separate from the image. Use
docker commitonly for experiments, and rebuild from a Dockerfile for anything you keep. - Counting instructions instead of bytes. Having many layers is rarely the problem. Large layers are. The number of layers matters far less than what each one contains.
Summary of the model
- An image is a manifest, a configuration and an ordered list of read-only layers, each identified by a digest.
- A layer is an archive of filesystem changes, including whiteout markers for deletions.
- A union filesystem merges the layers, and a container adds one writable layer on top with copy-on-write.
RUN,COPYandADDcreate layers with content. Most other instructions are metadata.- Image size is roughly the sum of its layer sizes, so bytes written in any layer are paid for even if a later layer hides them.
Exercise
You build an image with RUN curl -O https://example.com/data.tar.gz, then RUN tar -xzf data.tar.gz, then RUN rm data.tar.gz. The final container does not contain the archive, yet the image is still large. Why, and how would you change the Dockerfile so the archive does not add to the image size?
Show answer
Each RUN creates its own layer. The first layer stores the downloaded archive, and the rm in the third layer only adds a whiteout marker that hides it. The archive bytes stay in the first layer and are still part of the image. Combine the steps into one instruction, such as RUN curl -O https://example.com/data.tar.gz && tar -xzf data.tar.gz && rm data.tar.gz, so the archive is deleted before the layer is committed. Piping curl straight into tar would also avoid writing the archive at all.
Exercise
Which of these instructions adds file content to a new layer: ENV, COPY, USER, RUN? What size does docker history show for the others?
Show answer
COPY and RUN add file content to a new layer, whenever they change the filesystem. ENV and USER only update image metadata, so docker history shows 0B for them.