Images & Layers
An image is not one big file. It is an ordered stack of layers, each layer holding the files that one build step added, changed or deleted, plus a small JSON config (default command, environment, exposed ports, user). When you start a container, Docker stacks the layers on top of each other and adds one more thin writable layer for that container.
container layer (read-write) <- your changes while the container runs
-----------------------------
layer 3: COPY app.py /app \
layer 2: RUN pip install flask | image layers (read-only, shared)
layer 1: python:3.12-slim base /Looking at images
docker image ls
docker image history python:3.12-slim
docker image inspect python:3.12-slim --format '{{.RootFS.Layers}}'Sample output (abridged):
REPOSITORY TAG IMAGE ID CREATED SIZE
python 3.12-slim 1d7b2c3e4f5a 2 weeks ago 124MB
nginx 1.27 9a8b7c6d5e4f 3 weeks ago 192MB
IMAGE CREATED CREATED BY SIZE
1d7b2c3e4f5a 2 weeks ago CMD ["python3"] 0B
<missing> 2 weeks ago RUN /bin/sh -c set -eux; ... python ... 38.4MB
<missing> 2 weeks ago ENV PYTHON_VERSION=3.12.11 0B
<missing> 2 weeks ago # debian.sh --arch 'amd64' ... 'bookworm' ... 74.8MBSteps like ENV and CMD only change the config, so they add 0-byte entries. Steps that touch files (RUN, COPY, ADD) create real layers.
How the stacked filesystem works
Docker uses a union filesystem (overlayfs on Linux). To read a path, it looks from the top layer down and returns the first match. Deleting a file in an upper layer does not remove it from the lower one; it records a whiteout marker that hides it. The model below implements that lookup.
DELETED = object() # a whiteout marker
layers = [
{"/etc/os-release": "Debian 12", "/usr/bin/python3": "<binary>", "/tmp/setup.sh": "install..."},
{"/app/requirements.txt": "flask==3.1.1", "/tmp/setup.sh": DELETED},
{"/app/app.py": "print('v1')"},
]
container_layer = {}
def read(path):
for layer in [container_layer] + layers[::-1]: # top to bottom
if path in layer:
value = layer[path]
return "No such file" if value is DELETED else value
return "No such file"
def write(path, text):
container_layer[path] = text # copy-on-write
print(read("/app/app.py"))
print(read("/tmp/setup.sh"))
write("/app/app.py", "print('patched')")
print(read("/app/app.py"))
print("image layer still has:", layers[2]["/app/app.py"])print('v1')
No such file
print('patched')
image layer still has: print('v1')
Two consequences matter in practice:
- Deleting a file in a later step does not make the image smaller. The bytes are still in the lower layer, merely hidden. Clean up in the same
RUNstep that created the files. - Writing in a container is copy-on-write. The first time a container modifies a file from the image, the whole file is copied up into its writable layer.
Layers are shared
Each layer is identified by the SHA-256 digest of its content. Two images built on the same base reuse the same base layers, both on disk and when pulling: Docker downloads only the layers it does not have yet.
import hashlib
def digest(content):
return "sha256:" + hashlib.sha256(content.encode()).hexdigest()[:12]
base = [("debian bookworm files", 75), ("python 3.12 runtime", 38)]
images = {
"shop-api": base + [("flask + gunicorn", 12), ("shop api code", 1)],
"blog-api": base + [("flask + gunicorn", 12), ("blog api code", 2)],
"worker": base + [("celery", 9), ("worker code", 1)],
}
store = {}
naive_total = 0
for name, layers in images.items():
size = sum(mb for _, mb in layers)
naive_total += size
for content, mb in layers:
store[digest(content)] = mb
print(f"{name:<9} {len(layers)} layers, {size} MB")
print(f"sum of image sizes: {naive_total} MB")
print(f"unique layers on disk: {len(store)}, {sum(store.values())} MB")
print("base layer id:", digest("debian bookworm files"))shop-api 4 layers, 126 MB
blog-api 4 layers, 127 MB
worker 4 layers, 123 MB
sum of image sizes: 376 MB
unique layers on disk: 7, 138 MB
base layer id: sha256:8f8be0dbea30
That is why docker image ls can list images whose sizes add up to more than your disk actually uses: the column shows each image's full size, counting shared layers every time. docker system df shows the real usage.
Image IDs, digests and dangling images
| Identifier | Example | What it identifies |
|---|---|---|
| Name and tag | python:3.12-slim |
A movable label; it can point to a different image tomorrow |
| Image ID | 1d7b2c3e4f5a |
The hash of the image config on your machine |
| Repo digest | python@sha256:4f1c… |
The exact manifest in the registry; never changes |
When you rebuild myapp:latest, the tag moves to the new image and the old one becomes dangling, shown as <none>:<none>. Remove those with docker image prune.
docker image ls --filter dangling=true
docker image pruneTip: when you need repeatable builds, refer to the base image by digest (
FROM python:3.12-slim@sha256:...). A tag is a convenience; a digest is a guarantee.
Test yourself
A Dockerfile downloads a 200 MB archive in one RUN step and deletes it in the next RUN step. How much does the image grow?
- 0 MB, it was deleted
- About 200 MB, because the earlier layer still contains the file
- 100 MB
- It depends on the tag
Why does pulling a second image built on the same base usually go faster?
- Docker compresses it twice
- Layers are content-addressed, so already present base layers are not downloaded again
- The registry caches it for you
- Tags are shorter
What is a dangling image?
- An image that failed to build
- An image without a name or tag, usually left behind when a tag moved to a newer build
- An image larger than 1 GB
- An image currently used by a container