Layering & Copy-on-Write

Difficulty: Advanced

Question

How does Docker's layering and Copy-on-Write (CoW) mechanism work?

Answer

Docker images are a stack of read-only layers. When a container is started, a new writable 'container layer' is added on top.

If you modify a file from the image, Docker copies the file from the read-only layer into the writable layer (Copy-on-Write) and applies the change there. This allows multiple containers to share the same base image layers without conflict.

Code examples

Visualizing layers

# See the size and command of each layer
docker history my-image

Each line in 'history' corresponds to an instruction in the Dockerfile that created a layer.

Key points

Concepts covered

Filesystem, OverlayFS, Efficiency