Full Byte Developer.

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.

Published here , updated · 9 sources

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. For process wording, see 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].

One image, two containers FROM base (read-only) RUN packages (read-only) COPY app (read-only) Container A writable layer Container B writable layer docker rm drops only the writable top; image layers stay shared [1][3]

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
# syntax=docker/dockerfile:1

FROM ubuntu:22.04
LABEL org.opencontainers.image.authors="[email protected]"
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
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. See also Docker Swarm vs Kubernetes plain.

Secrets that get COPYed 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.

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.

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

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.
An image is an immutable layer stack. A container adds one writable layer, then drops it.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

What is the difference between an image and a container?

An image is a read-only template made of stacked layers. A container is a runnable instance of that image plus a thin writable top layer. Delete the container and that writable layer goes; the image stays.

If I delete a file inside a running container, is it gone from the image?

No. On OverlayFS, deletes create whiteouts in the container's upperdir. Image layers stay untouched. Other containers started from the same image still see the original file.

Do Engine 29.0 fresh installs still use overlay2 on disk?

Docker Docs say Engine 29.0 and later use the containerd image store by default for fresh installs (snapshotters instead of classic graph drivers). The layer-stack idea still applies; on-disk layout commands may differ until you migrate.

Sources

Next in this stack