Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 33 of 8021. Container FundamentalsFree lesson

Implementing Copy-on-Write Strategy

Demonstrate how the container runtime uses copy-on-write to defer file duplication until a write operation is actually performed by the application.

In this lesson, you will learn how the Copy-on-Write (CoW) strategy allows multiple containers to share the same base files without duplicating them until a change is absolutely necessary.

The Problem: Redundancy

Imagine you have a base image containing a 500MB operating system. If you run 10 containers from that image, you wouldn't want to copy that 500MB file 10 times—that would waste 5GB of disk space. Instead, container runtimes use a Union File System combined with a Copy-on-Write strategy.

How Copy-on-Write Works

When a container starts, the base image layers are mounted as "read-only." You can think of these as a shared library that every container can read from, but no container can modify.

When your application needs to modify a file—for example, if a log file is updated or a configuration file is edited—the CoW strategy kicks in:

  1. The Request: The application attempts to write to config.json.
  2. The Check: The runtime checks if the file exists in the writable "top layer" of the container.
  3. The Copy: Since the file is currently in the read-only image layer, the runtime copies the file from the image layer up to the container's writable layer.
  4. The Write: The application performs its write operation on this new, private copy.

The original file in the base image remains untouched and is still available for other containers to read.

A Quick Illustration

If you have a file /app/data.txt in your image:

  • Reading: When your app reads /app/data.txt, it points directly to the image layer. Zero bytes are copied.
  • Writing: When your app runs echo "new data" > /app/data.txt, the runtime instantly copies data.txt to the thin writable layer at the top of the stack. Your change happens there.

This process is completely transparent; the application thinks it has its own private filesystem, but it is actually sharing the bulk of the data with other containers on the host. This makes container startup nearly instantaneous and highly storage-efficient.

Key Takeaway: Copy-on-Write saves space and time by sharing read-only image layers across containers and only duplicating specific files into a private, writable layer at the exact moment a write operation occurs.