Docker & Containers (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
Container Storage & UnionFS / Overlay2: How does the Copy-on-Write (CoW) mechanism work in Docker?
senior LevelMost AskedCode ExampleDocker & ContainersSystem Design
In Simple Words: Docker images are built as a stack of immutable, read-only layers. When a container runs, Docker attaches a single, thin, read-write layer on top known as the Container Layer. Docker implements this filesystem stack using the Overlay2 storage driver (Linux OverlayFS).
sql
+-------------------------------------------------------+
| Container Read-Write Layer (Modified files, temp data)| <- "upperdir"
+-------------------------------------------------------+
| Layer 3: Application Code (Read-Only) | \
+-------------------------------------------------------+ |
| Layer 2: Installed Runtime / Node / Python (Read-Only)| | <- "lowerdir" (Immutable image layers)
+-------------------------------------------------------+ |
| Layer 1: Base OS Debian/Alpine (Read-Only) | /
+-------------------------------------------------------+
|
v
[ Merged View (What the container sees) ]
OverlayFS Directory Structure
lowerdir: The read-only base image layers joined together with colon-separated paths.upperdir: The writable container layer where file modifications, new files, and deletes are recorded.workdir: Internal scratch directory used by the Linux kernel to prepare atomic copy-on-write operations.merged: The unified mount point presented to the container process.
Copy-on-Write (CoW) Lifecycle
- Reading a file: The driver checks
upperdir. If the file is not there, it reads down intolowerdirwith zero performance overhead. - Modifying an existing file: The driver copies the file from the read-only
lowerdirup intoupperdir, and modifications happen there. The original layer file remains untouched. - Deleting a file: Creates a special "whiteout" character device file in
upperdirthat masks the file inlowerdir, rendering it invisible inmerged.