CodePark/ questions / Images, containers & the runtime
START PRACTICINGPRACTICE
Backend question · Docker › Images, containers & the runtime

How does the container filesystem work, and why can 20 containers from the same 1 GB image use far less than 20 GB of disk?

All 20 containers share the same read-only image layers, so those layers exist on disk only once. Each container stores only its own changes.

How it works: an image is a stack of read-only layers. When a container starts, the storage driver stacks those layers. It adds one thin writable layer on top and shows everything as a single filesystem. On most Linux hosts the storage driver is overlay2.

Each container writes its changes only to its own writable layer. What if a container changes a file from a lower, read-only layer? The driver first copies the file up into the writable layer, then changes it there. This is called copy-on-write.

This also explains two things:

  • Writes to the container filesystem are slower than writes to a volume.
  • That data disappears when you remove the container.
  • Image layers are read-only and shared by all containers.
  • Each container gets its own thin writable layer.
  • overlay2 shows the stacked layers as one filesystem.
  • Changing a file from a lower layer first copies it up (copy-on-write).
  • The writable layer is deleted with the container.