---
title: "Docker Image Layers, Build Caching, and Content-Addressable Storage"
date: "2026-11-17T09:30:00+07:00"
description: "Explore how Docker constructs images using content-addressable read-only layers, layer caching mechanics, and BuildKit optimization strategies."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/image-layers-caching-content-addressable-storage.jpg"
alt: "Diagram of stacked read-only Docker image layers with content-addressable SHA hashes and a writable container layer on top."
tags: ['docker', 'containers', 'buildkit', 'performance', 'devops']
---

At the heart of Docker's storage efficiency is the concept of **stacked, read-only filesystem layers**. Every instruction in a `Dockerfile` that alters files or directories produces a distinct layer. 

By leveraging **Content-Addressable Storage (CAS)**, Docker shares identical image layers across containers on the host, dramatically reducing disk utilization and build times. Understanding layer caching mechanisms allows engineers to structure `Dockerfile`s for maximum cache reuse and minimal image footprints.

---

## 1. Anatomy of Image Layers and Content Addressing

A Docker image is an ordered stack of read-only tarball layers plus an execution configuration JSON file.

```
+-------------------------------------------------------------+
|             Writable Container Layer (Read-Write)           |
+-------------------------------------------------------------+
| Layer 4: RUN npm build          (Read-Only Layer Hash: 8a7c) |
+-------------------------------------------------------------+
| Layer 3: COPY src/ .            (Read-Only Layer Hash: 3b9e) |
+-------------------------------------------------------------+
| Layer 2: COPY package.json .    (Read-Only Layer Hash: 1f2d) |
+-------------------------------------------------------------+
| Layer 1: FROM node:22-alpine    (Read-Only Base Layers)      |
+-------------------------------------------------------------+
```

### Content-Addressable Identifiers (CAS)

In early Docker versions, layers were identified by random IDs. Since Docker 1.10, Docker uses **Content-Addressable Storage**:
- **DiffID:** The SHA-256 hash of the uncompressed layer tarball content.
- **Layer Digest:** The SHA-256 hash of the compressed layer tarball as stored in the registry.
- **ChainID:** A cryptographic computation combining a layer's DiffID with all parent DiffIDs below it (`ChainID(n) = SHA256(ChainID(n-1) + " " + DiffID(n))`).

Because layer IDs depend strictly on their binary content, two entirely different images that share the exact same `FROM alpine:3.20` base layer will store and reference **only one single copy** of those base layer files in `/var/lib/docker/overlay2/`.

---

## 2. Inspecting Layer Histories and Disk Layout

You can examine layer creation, sizes, and instruction origins using `docker history`:

```bash
docker history node:22-alpine
```

*Output snippet:*
```text
IMAGE          CREATED        CREATED BY                                      SIZE      COMMENT
c16e788e285d   2 days ago     CMD ["node"]                                    0B        buildkit.dockerfile.v0
<missing>      2 days ago     COPY /usr/local/bin/docker-entrypoint.sh /usr…  388B      buildkit.dockerfile.v0
<missing>      2 days ago     ENV NODE_VERSION=22.11.0                        0B        buildkit.dockerfile.v0
<missing>      2 weeks ago    /bin/sh -c #(nop) ADD file:a8856011400898528…   7.8 MB    
```

*Note:* Metadata-only instructions (`ENV`, `CMD`, `EXPOSE`, `LABEL`) consume **0 bytes** because they update the image manifest JSON rather than producing filesystem diff layers.

---

## 3. The Build Cache Mechanism: How Cache Invalidation Works

During `docker build` (or BuildKit execution), the builder evaluates `Dockerfile` instructions step by step from top to bottom. For each instruction, BuildKit checks if a cached layer already exists with identical execution semantics.

```
       Dockerfile Steps                          Build Cache Status

   1. FROM node:22-alpine             -->  [CACHED] (Reused base layers)
   2. WORKDIR /app                    -->  [CACHED] (No file changes)
   3. COPY package.json .             -->  [CACHED] (package.json checksum matches)
   4. RUN npm install                 -->  [CACHED] (Commands & inputs unchanged)
   5. COPY . .                        -->  [INVALIDATED!] (Source file edited)
   6. RUN npm run build               -->  [BUILD EXECUTED] (Cache missed)
```

### Rules of Cache Invalidation

1. **Instruction String Matching:** For `RUN` commands, the builder compares the exact string text of the command against previous cache entries.
2. **File Checksum Verification:** For `COPY` and `ADD` commands, the builder computes a SHA-256 checksum of every copied file (content + file metadata). If a single file's checksum differs, **that layer cache is invalidated**.
3. **Cascade Invalidation:** Once a layer cache is invalidated, **all subsequent build steps lose cache reuse** and must re-run from scratch.

---

## 4. Optimizing Dockerfiles for Cache Efficiency

To maximize build speed, structure your `Dockerfile` so that infrequently changing instructions appear first, and frequently changing files appear as late as possible.

### Antipattern: Global Copy Before Dependency Installation

```dockerfile
# POOR PRACTICE: Invalidates npm install on ANY source code change!
FROM node:22-alpine
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]
```

### Optimized Pattern: Layer-Separated Dependencies

```dockerfile
# BEST PRACTICE: Reuses npm install cache when package.json is untouched
FROM node:22-alpine
WORKDIR /app

# Step A: Copy dependency manifests only
COPY package.json package-lock.json ./
RUN npm ci

# Step B: Copy application source code (frequently edited)
COPY src/ ./src
COPY public/ ./public

CMD ["npm", "start"]
```

---

## 5. Advanced BuildKit Cache Mounts

Modern Docker builds using BuildKit (default in Docker 23+) support persistent cache mounts via `RUN --mount=type=cache`. This allows package managers (`npm`, `apt`, `pip`, `go`, `cargo`) to retain package download caches **across independent build executions**, even when step caches are invalidated.

```dockerfile
# syntax=docker/dockerfile:1
FROM golang:1.24-alpine AS builder
WORKDIR /app

COPY go.mod go.sum ./
# Preserve Go module cache across builds
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download

COPY . .
# Preserve Go build compilation cache across builds
RUN --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -o /app/server .
```

---

## Key Takeaway

**Takeaway:** Docker images store data as an ordered stack of content-addressable read-only layers. Because cache invalidation cascades downwards from the first modified step, ordering instructions from least-frequently changed (`package.json`, `apt-get`) to most-frequently changed (`src/`) guarantees fast, reproducible builds and minimal storage overhead.

---

## Sources

- [Docker Documentation: Best practices for writing Dockerfiles](https://docs.docker.com/build/building/best-practices/)
- [Docker Documentation: BuildKit cache mounts](https://docs.docker.com/build/cache/advanced/)
- [OCI Image Layer Filesystem Changesets Specification](https://github.com/opencontainers/image-spec/blob/main/layer.md)
