# How Docker works: images, containers, and layers

> Images are immutable layer stacks. A container adds one writable layer on top, then drops it when deleted.

Source: https://fullbytedeveloper.com/blog/how-docker-works-images-containers-layers
Published here: 2026-11-20, updated 2026-12-03

A Docker image is a read-only stack of filesystem layers. A container is that image plus one thin writable layer where runtime changes land. Remove the container and the writable layer disappears; the image remains for the next start [1][3]. OverlayFS names and a local demo below make the split concrete.

Intermediate Part 2 after [why Docker was introduced](/blog/why-docker-was-introduced). For process wording, see [what is a container](/blog/what-is-a-container).

## Quick start: picture the image stack before you run anything

Docker Docs describe an image as a read-only template with instructions for starting a container, often built FROM another image with added customization [1]. Storage drivers spell out the runtime split: the main difference between a container and an image is the top writable layer. All container writes go there, and deleting the container deletes that layer while the image underneath stays intact [3].

Several containers can share one image and still keep separate writable tops [3]. That sharing is why layer caching matters when you build: identical layer content can be reused across tags and machines [2][7].

<figure>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 300" role="img" aria-label="One image stack shows FROM base, RUN packages, and COPY app as read-only layers; arrows fork into Container A and Container B, each with its own writable layer, while a footer notes docker rm drops only the writable top and shared image layers stay.">
  <defs>
    <marker id="arrowDockerLayers" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">
      <path d="M0,0 L8,3 L0,6 Z" fill="#14b8a6"/>
    </marker>
  </defs>
  <rect x="0" y="0" width="720" height="300" rx="12" fill="#0b1f3a"/>
  <text x="24" y="36" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="16" font-weight="700">One image, two containers</text>
  <rect x="24" y="56" width="220" height="44" rx="8" fill="#123052" stroke="#64748b" stroke-width="2"/>
  <text x="36" y="84" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">FROM base (read-only)</text>
  <path d="M134 100 V116" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowDockerLayers)"/>
  <rect x="24" y="120" width="220" height="44" rx="8" fill="#123052" stroke="#64748b" stroke-width="2"/>
  <text x="36" y="148" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">RUN packages (read-only)</text>
  <path d="M134 164 V180" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowDockerLayers)"/>
  <rect x="24" y="184" width="220" height="44" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="36" y="212" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">COPY app (read-only)</text>
  <path d="M244 206 H300" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowDockerLayers)"/>
  <rect x="300" y="168" width="140" height="76" rx="8" fill="#123052" stroke="#f59e0b" stroke-width="2"/>
  <text x="312" y="200" fill="#f59e0b" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Container A</text>
  <text x="312" y="224" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">writable layer</text>
  <path d="M244 206 H480" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#arrowDockerLayers)"/>
  <rect x="480" y="168" width="140" height="76" rx="8" fill="#123052" stroke="#f59e0b" stroke-width="2"/>
  <text x="492" y="200" fill="#f59e0b" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Container B</text>
  <text x="492" y="224" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">writable layer</text>
  <text x="24" y="272" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">docker rm drops only the writable top; image layers stay shared [1][3]</text>
</svg>
</figure>

*One image stack builds FROM base, RUN packages, and COPY app as shared read-only layers. Arrows fork into Container A and Container B, each with its own writable top. docker rm drops only that writable layer; the shared image layers stay for the next start.*

On a host with Engine installed, Docker Docs teach layer inspection with `docker image history` on an image such as `docker/welcome-to-docker` [1][6]:

```bash
docker pull docker/welcome-to-docker
docker image ls
docker image history docker/welcome-to-docker
```

Listed sizes reflect uncompressed layer size, not necessarily download size when layers dedupe [1]. This draft environment could not open the Docker socket, so digests and history tables are not pasted from invented runs. Refresh the printed table on your host. Optional full commands:

```bash
docker image history --no-trunc docker/welcome-to-docker
```

## Walk the layer cake a Dockerfile builds

Each filesystem-changing instruction in a Dockerfile adds a layer. Layers are content-addressable and reusable when two images need the same bytes [2][3][7]. Docker's Dockerfile best-practices post stresses ordering: put stable instructions early so cache hits survive, and keep cleanup inside the same `RUN` that created temp files so dead weight does not freeze into an earlier layer [8].

Teaching shape from the storage-drivers page [3]:

```dockerfile title="Dockerfile"
# syntax=docker/dockerfile:1

FROM ubuntu:22.04
LABEL org.opencontainers.image.authors="org@example.com"
COPY . /app
RUN make /app
RUN rm -r $HOME/.cache
CMD python /app/app.py
```

Docker Docs note on that example: `FROM` pulls base layers; `LABEL` and `CMD` change metadata without new filesystem layers; `COPY` and file-changing `RUN` lines become layers; deleting files in a later layer does not shrink earlier ones [3].

Docker Learn (verified 2026-10-21) uses a small Node service and suggests formatting history with `docker image history --format 'table {{.CreatedBy}}\t{{.Size}}'` [7]. Metadata-only instructions like `EXPOSE` and `CMD` may show `0B` [7]. Prefer a Dockerfile over `docker container commit` for real builds; commit appears in docs mainly as a lab trick [2].

Docker layer sharing reuses the same dedupe idea for filesystem layers.

## Simulate OverlayFS with directories on any machine

Classic Linux storage uses kernel OverlayFS. Docker's `overlay2` driver maps read-only image layers to `lowerdir` entries, container writes to `upperdir`, and the process view to `merged` [4]. The first write to an existing image file copies the whole file into `upperdir`. Deletes add whiteouts in `upperdir`; image lowers stay untouched [4].

This draft environment has no usable Docker socket. The script below stacks two read-only directories and one writable upper to show shadowing and a whiteout. Save it as `overlay_demo.py`, then run it:

```bash
python3 overlay_demo.py
```

```python title="overlay_demo.py"
#!/usr/bin/env python3
"""Stacked read-only image layers plus one writable container layer (teaching demo)."""
import shutil
import tempfile
from pathlib import Path

def read_merged(lowers: list[Path], upper: Path) -> dict[str, str]:
    table: dict[str, str] = {}
    for low in lowers:
        for p in low.rglob("*"):
            if p.is_file():
                rel = p.relative_to(low).as_posix()
                table[rel] = f"image layer {low.name}"
    for p in upper.rglob("*"):
        if p.is_file():
            rel = p.relative_to(upper).as_posix()
            if rel == ".wh.hosts":
                table.pop("etc/hosts", None)
                continue
            table[rel] = f"container layer {upper.name}"
    return dict(sorted(table.items()))

root = Path(tempfile.mkdtemp())
try:
    base = root / "layer-base"
    added = root / "layer-app"
    upper = root / "layer-writable"
    for d in (base, added, upper):
        d.mkdir()
    (base / "etc").mkdir()
    (base / "etc" / "hosts").write_text("127.0.0.1 localhost\n", encoding="utf-8")
    (added / "app").mkdir()
    (added / "app" / "main.py").write_text("print('from image')\n", encoding="utf-8")
    (upper / "app").mkdir()
    (upper / "app" / "main.py").write_text("print('from container')\n", encoding="utf-8")
    (upper / ".wh.hosts").write_bytes(b"")
    merged = read_merged([base, added], upper)
    print("visible files in container view:")
    for rel, src in merged.items():
        print(f"  {rel}\t<- {src}")
    print("etc/hosts from image layers: removed via upper whiteout")
finally:
    shutil.rmtree(root)
```

Captured on 2026-12-03. Sandbox capture on the review host; re-run on your box before you treat the numbers as a lab result.

```text
visible files in container view:
  app/main.py	<- container layer layer-writable
etc/hosts from image layers: removed via upper whiteout
```

The writable layer replaced `app/main.py` and hid `etc/hosts` without erasing the read-only lowers on disk. That matches the teaching point in the OverlayFS driver page about copy-up writes and whiteouts [4]. If you later `docker commit` a container into a new tag, Docker freezes that writable diff into another read-only layer on a new image. That is why commit-based workflows balloon in size: every experiment adds a permanent layer instead of a Dockerfile line you can delete [2][8].

Use volumes or bind mounts when data must survive container deletion. The writable layer is ephemeral by design [3][4].

## Read size columns without double-counting layers

Storage drivers document `docker ps -s` as a way to see writable-layer use versus virtual size (image plus writable) [3]. Virtual size is not a bill you pay once per container when images share layers, so do not sum virtual sizes across siblings [3].

On your own Engine host after `docker run --name layer-demo -d docker/welcome-to-docker`, `docker ps -s` should list the container with separate size columns per the same page [3]. Remove the container with `docker rm -f layer-demo` and only the writable top goes [3].

## Footnote Engine 29 and the containerd image store

**Warning:** Docker Engine 29.0 and later enable the containerd image store by default on fresh installs, using snapshotters instead of classic graph drivers [5]. Upgraded hosts may keep legacy drivers until you migrate [5]. The mental model in this article still holds; paths under `/var/lib/docker/overlay2` may not match a fresh 29.x install [3][5].

Docker Docs suggest checking driver status with:

```bash
docker info -f '{{ .DriverStatus }}'
```

When the containerd image store is active, output should include `[[driver-type io.containerd.snapshotter.v1]]` per the containerd image store page [5]. Layer history concepts remain; only the on-disk layout and some inspection commands shift.

## Cache hits and ordering that pays rent

Build cache is the practical reason to care about layers. If `COPY . /app` lands before a package install that rarely changes, every source edit busts the package layer too [7][8]. Flip the order: install dependencies from a lockfile first, copy app sources later. Keep `apt-get update` and `apt-get install` in one `RUN` so the index and the packages share a layer, then clean lists in that same layer [8].

Multi-stage builds keep compiler toolchains out of the final image by copying only artifacts forward. That is still the same layer model: each stage is its own stack; you choose what crosses the boundary [2][7].

## Swarm and Kubernetes sit on top of this model

Orchestrators schedule containers; they do not replace the image versus writable-layer split. When you compare Swarm and Kubernetes plain language later, start from this page and [what is a container](/blog/what-is-a-container). See also [Docker Swarm vs Kubernetes plain](/blog/docker-swarm-vs-kubernetes-plain).

Secrets that get `COPY`ed into an image layer stay in that layer history even after you delete the file in a later instruction. That failure mode has its own field note: [your .env may be inside the Docker image](/blog/docker-env).

## Mistakes that confuse images with running processes

`docker rm` removes the container writable layer only. The image tag stays until you prune images explicitly [1][3].

A later `RUN rm` in a Dockerfile does not retroactively compress earlier layer blobs. Cleanup belongs in the same `RUN` that created the temp files [3][8].

Logs and SQLite files in the writable layer vanish on `docker rm`. Put durable data on named volumes or bind mounts [3][4].

On a containerd-only host, check `DriverStatus` before you chase files under classic `overlay2` paths [5].

Committing containers into "golden" production images skips cache-friendly Dockerfile ordering and freezes every experiment as a permanent layer [2][8].

## Depth: whiteouts versus real deletes

A whiteout is a marker in `upperdir` that hides a path from lower layers in the merged view [4]. The lower file bytes can still exist on disk for other containers that share those lowers. That is why deleting `/etc/hosts` inside one container does not rewrite the image everyone else started from [4]. The Python demo's `.wh.hosts` file is a teaching stand-in for that marker, not a claim that every driver uses that exact filename on disk.

Copy-up has a cost: the first write to a large file duplicates it into the writable layer even if you change one byte [4]. Workloads that rewrite huge files in place can balloon container size without growing the image. Volumes avoid that tax for data you meant to mutate anyway.

## Depth: what to say in a design review

Ask three questions before debating orchestrators. Where do image layers come from (Dockerfile versus commit)? What must survive `docker rm` (volumes versus writable layer)? Which Engine storage mode is the host on (classic overlay2 versus containerd snapshotter) [3][5]? Those answers settle most "where did my disk go" tickets without opening a Kubernetes rabbit hole.

Browse the [Dev explainers topic](https://fullbytedeveloper.com/blog/topic/dev-explainers).

Send this to the friend who runs containers daily yet confuses images with the running process.

Image: A stack of immutable translucent teal image layers with a single thin amber writable cap on top, and beside it the same cap peeling away and dissolving as a container cube vanishes, leaving the teal stack unchanged, on a dark navy field with no logos or typography.
https://fullbytedeveloper.com/media/how-docker-works-images-containers-layers/how-docker-works-images-containers-layers-venice.webp
An image is an immutable layer stack. A container adds one writable layer, then drops it.

## Sources

1. [Docker Docs: What is an image?, accessed 2026-11-20](https://docs.docker.com/get-started/docker-concepts/the-basics/what-is-an-image/)
2. [Docker Docs: Understanding the image layers, accessed 2026-11-20](https://docs.docker.com/get-started/docker-concepts/building-images/understanding-image-layers/)
3. [Docker Docs: Storage drivers, accessed 2026-11-20](https://docs.docker.com/engine/storage/drivers/)
4. [Docker Docs: OverlayFS storage driver, accessed 2026-11-20](https://docs.docker.com/engine/storage/drivers/overlayfs-driver/)
5. [Docker Docs: containerd image store, accessed 2026-11-20](https://docs.docker.com/engine/storage/containerd/)
6. [Docker Docs: docker image history, accessed 2026-11-20](https://docs.docker.com/reference/cli/docker/image/history/)
7. [Docker Learn: How image layers and the build cache work (verified 2026-10-21), accessed 2026-11-20](https://docs.docker.com/learn/content/how-image-layers-and-the-build-cache-work/)
8. [Docker Blog: Intro Guide to Dockerfile Best Practices, accessed 2026-11-20](https://www.docker.com/blog/intro-guide-to-dockerfile-best-practices/)
9. [GitHub Blog: Git's database internals I (packed object store), accessed 2026-11-20](https://github.blog/open-source/git/gits-database-internals-i-packed-object-store/)
