3 Hours

4. Understanding Docker Images and the Union Filesystem

Core Concepts

How Docker Images Are Built From Layers

Docker images are not monolithic files — they are composed of read-only layers stacked on top of each other. Understanding how layers work is the key to writing efficient Dockerfiles, optimizing image size, and leveraging Docker's build cache effectively. This module explains the union filesystem, layer caching, and copy-on-write in depth.

The Union Filesystem: How Multiple Layers Become One View

The union filesystem (OverlayFS is the modern default) allows multiple directories — each containing a filesystem — to be mounted on top of each other to appear as a single unified directory. Docker images are built as a stack of layers. The bottom layer is the base image (like `alpine` or `ubuntu`). Each instruction in the Dockerfile (`RUN`, `COPY`, `ADD`) adds a new layer on top. When you run a container, Docker adds one more writable layer on top of the read-only image layers. When a process in the container reads a file, Docker looks for it starting from the topmost layer and works down until it finds the file. When a process writes a file, Docker creates a copy in the writable layer — this is called copy-on-write. This design is incredibly efficient: multiple containers running from the same image share the same read-only layers, consuming only the extra writable layer (usually a few megabytes) per container. The union filesystem also enables Docker's layer caching — if a layer hasn't changed, Docker can reuse it.

Text
Layer Stack Visualization for a Typical Node.js App:

Container Writable Layer    ← Your app writes logs, temp files here (per-container)
Layer 4: CMD               ← Metadata only (no files)
Layer 3: COPY . .          ← Your application source code
Layer 2: RUN npm install   ← node_modules directory
Layer 1: COPY package.json ← Dependency manifest
Layer 0: FROM node:18      ← Base operating system and Node.js runtime

Union Filesystem → When you look inside the container, you see ALL files from ALL layers merged together.

Inspecting Image Layers and Understanding Their Impact

The `docker history` command reveals the layer structure of an image. Each line represents one layer, showing the command that created it, the size of the layer, and how long ago it was created. Pay close attention to the size column — large layers indicate that the command added many files or performed extensive operations. The `docker inspect` command provides even more detail, including the exact layer IDs and the image's metadata. Understanding which layers are large helps you optimize your Dockerfiles. For example, if `RUN apt-get install -y build-essential` creates a 200MB layer, you might want to combine it with cleanup commands in the same layer. If `COPY . .` creates a large layer, check your `.dockerignore` file to ensure you are not copying unnecessary files like `node_modules`, `.git`, or `*.log`. Each layer adds overhead — even if the files are later deleted in a subsequent layer, the previous layer still contains them. This is why chaining commands (e.g., `RUN apt-get update && apt-get install && rm -rf /var/lib/apt/lists/*`) in a single `RUN` instruction is crucial: it prevents the intermediate files from being preserved in a separate layer.

Bash
# Inspect layer history of the alpine image
docker history alpine:latest

# Show full commands (not truncated)
docker history --no-trunc alpine:latest

# For a Node.js app image, examine layer sizes
docker history my-node-app:latest
# Look for unexpectedly large layers

# Get detailed JSON metadata including layer IDs
docker inspect alpine:latest | grep -A 10 "RootFS"

# Compare two images to see shared layers
docker images --tree  # Not available in newer Docker, use dive tool instead

# Save image to tar and inspect (advanced)
docker save alpine:latest -o alpine.tar
tar -tvf alpine.tar | head -20

Copy-on-Write (CoW): Why Multiple Containers Don't Duplicate Data

Copy-on-Write is the mechanism that makes containers efficient. When you run a container, Docker adds a thin writable layer on top of the read-only image layers. This writable layer starts empty. When the container needs to modify a file that exists in a lower layer, Docker copies that file from the read-only layer into the writable layer, then performs the modification on the copy. This is called copy-up or copy-on-write. The key insight is that copying only happens when a file is modified — if the container only reads files, no copy ever occurs. This means that 100 containers running from the same 500MB image only consume 500MB for the image (shared) plus approximately 10-50MB per container for their writable layers. Without CoW, you would need 100 × 500MB = 50GB. CoW also affects performance: the first write to a file is slower because of the copy operation, but subsequent writes are normal speed. For most workloads, this overhead is negligible. You can observe CoW in action by running a container, modifying a large file, and watching disk usage with `docker diff` before and after.

Bash
# Run two containers from the same image
docker run -d --name app1 nginx:alpine
docker run -d --name app2 nginx:alpine

# Check disk usage — both containers share the image layers
docker system df

# See what files changed in a container (CoW layer)
docker run -d --name test alpine sleep 1000
docker exec test touch /tmp/newfile.txt
docker diff test
# A = file added, C = file changed, D = file deleted

# Check actual disk usage of writable layer
docker ps -s
# Shows SIZE (writable layer) and VIRTUAL SIZE (total with shared image)

# Commit a container's changes to a new image (creates new layer)
docker commit test mymodified:latest
docker history mymodified:latest

Layer Caching: Why Dockerfile Order Matters

Docker caches layers to speed up subsequent builds. When you build an image, Docker checks each instruction sequentially. If it has a cached layer for that instruction AND the instruction text is exactly the same AND any files referenced (`COPY`, `ADD`) have not changed, Docker reuses the cached layer. This is why the order of instructions in your Dockerfile dramatically affects build performance. Best practice: put instructions that change infrequently at the top, and instructions that change frequently at the bottom. For a Node.js app, you would copy `package.json` and `package-lock.json` first, then run `npm install`. These files change rarely, so the `npm install` layer is cached most of the time. Then you copy the rest of your source code — which changes on every build. This way, when you change a single line of your app code, Docker reuses the cached `npm install` layer (which took 30 seconds) and only rebuilds the final `COPY . .` layer (which takes milliseconds). If you copy your source code first, changing any file invalidates the cache for EVERY subsequent instruction, forcing `npm install` to run again on every build.

Text
# OPTIMIZED DOCKERFILE — maximizes cache reuse
FROM node:20-alpine
WORKDIR /app

# Copy dependency files first (change infrequently)
COPY package*.json ./
RUN npm ci

# Copy source code last (changes every build)
COPY . .

CMD ["node", "app.js"]
Text
# PESSIMIZED DOCKERFILE — cache is useless
FROM node:20-alpine
WORKDIR /app

# Copy everything first — ANY file change invalidates all subsequent layers!
COPY . .

# This runs on EVERY build, even if package.json didn't change
RUN npm ci

CMD ["node", "app.js"]

Knowledge Check

Ready to test your understanding of 4. Understanding Docker Images and the Union Filesystem?

Back