Images, overlay layers, the build cache and what not to bake in
Open an OCI image to see its index, manifests, config and layers; tell tags from digests and pin by digest; watch the overlay filesystem copy up and hide files; and use the build cache, secret mounts and .dockerignore so images build fast and carry nothing they should not.
Contentsand lesson path
On this page
- Why it matters
- What is inside an image
- Tags move, digests do not
- Layers at run time: the overlay filesystem
- How the build cache decides what to rerun
- What not to bake into an image
- Check your understanding
- Apply it
- Review prompt
Lessons of Containerization
- A container is a process with boundaries Concept · 15 min
- Images, overlay layers, the build cache and what not to bake in Concept · 20 min
- Lab: from a naive Dockerfile to a slim, non-root multi-stage image Lab · 30 min
- Running containers deliberately: ports, volumes, bind mounts, devices and GPUs, environment and logs Worked example · 25 min
- Lab: an app and its database with Compose, health checks and a live-reload loop Lab · 30 min
- Check: debug three broken containers Knowledge check · 8 questions
What you will learn
- Explain how containers isolate processes with namespaces and cgroups, and how image layers, tags and digests relate in the OCI image format.
- Write a multi-stage Dockerfile that yields a small image running as a non-root user, with cache-friendly layer order and a .dockerignore.
01. Why it matters
The image is the thing you ship, so its faults ship too. Three of them come up again and again: builds that are slow because the cache keeps missing, images that stay huge even though a later step deleted the big file, and a token or a model file that ended up inside an image pushed to a registry, where anyone who can pull the image can read it. All three follow directly from how images are stored and built.
The outputs below come from Docker Engine 29.8, which uses the containerd image store by default on new installs. An Engine upgraded from an older version may still use the classic overlay2 store: the concepts are identical, but docker images shows a single SIZE column and image IDs are computed differently.
02. What is inside an image
An OCI image (the format standardised by the Open Container Initiative, which Docker, Podman and Kubernetes all use) is a handful of JSON documents and compressed tar archives. Every piece is stored and referenced by the SHA-256 digest of its bytes:
- An index lists one manifest per platform, such as
linux/amd64andlinux/arm64. This is what lets one name serve laptops and servers with different CPUs. - A manifest describes one platform's image: one config and an ordered list of layers, each with its digest and size.
- The config holds the runtime defaults (environment, user, working directory,
CMDandENTRYPOINT, exposed ports, health check), the build history, and the digest of each uncompressed layer. - Each layer is a tar archive of filesystem changes, usually gzip-compressed.
Because each document names the next by digest, changing a single byte in a layer changes that layer's digest, the manifest's digest and the index's digest. That chain is why a digest is a name you can trust. You can read an image's index straight from the registry, without pulling it:
docker buildx imagetools inspect python:3.12-slim | head -n 8Name: docker.io/library/python:3.12-slim
MediaType: application/vnd.oci.image.index.v1+json
Digest: sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
Manifests:
Name: docker.io/library/python:3.12-slim@sha256:2b4f19dae3a7…
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: linux/amd64Without head, the output continues with annotations (the version label reads 3.12.15-slim-trixie), then seven more platforms, each followed by an attestation manifest (Platform: unknown/unknown) that carries build provenance. Locally, docker image inspect reads the config of the platform you pulled:
docker image inspect python:3.12-slim \
--format '{{.Os}}/{{.Architecture}} cmd={{.Config.Cmd}} layers={{len .RootFS.Layers}}'linux/amd64 cmd=[python3] layers=404. Layers at run time: the overlay filesystem
When a container starts, its image layers are stacked read-only and a thin, empty writable layer is added on top. An overlay (union) filesystem presents the stack as one directory tree. A read falls through to the highest layer that has the file. The first write to a file from the image copies it up into the writable layer (copy-up) and changes the copy. Deleting a file from the image cannot touch the read-only layer, so the writable layer records a whiteout that hides it. docker diff lists what the writable layer holds:
docker run --name ctr-diff alpine:3.24 \
sh -c 'echo hello > /tmp/note.txt && rm /etc/motd && echo "# changed" >> /etc/profile'
docker diff ctr-diff
docker rm ctr-diffC /tmp
A /tmp/note.txt
C /etc
C /etc/profile
D /etc/motd
ctr-diffA is added, C changed (copied up) and D deleted (a whiteout). The writable layer belongs to the container and disappears with docker rm; lesson 4 covers volumes for data that must outlive it.
Builds follow the same rules. Each RUN, COPY and ADD instruction produces one layer that records what changed. A file deleted in a later layer is only hidden, and the earlier layer still carries its bytes. Compare two Dockerfiles that create and delete a 50 MB file, in separate steps and in one step:
FROM alpine:3.24
RUN head -c 50000000 /dev/urandom > /blob.bin
RUN rm /blob.binFROM alpine:3.24
RUN head -c 50000000 /dev/urandom > /blob.bin && rm /blob.bindocker build -q -f Dockerfile.split -t layers:split .
docker build -q -f Dockerfile.joined -t layers:joined .
docker images layers
docker history layers:split --format 'table {{.CreatedBy}}\t{{.Size}}'sha256:30163d53ddd69720b2872c95b706dc9313558a511f21e2c5d2ae50f834088592
sha256:4decc74a6f499ed37901af0951a665b916858a6214ff6570d2da2767e183067b
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
layers:joined 4decc74a6f49 12.1MB 3.63MB
layers:split 30163d53ddd6 112MB 53.6MB
CREATED BY SIZE
RUN /bin/sh -c rm /blob.bin # buildkit 4.1kB
RUN /bin/sh -c head -c 50000000 /dev/urandom… 50MB
CMD ["/bin/sh"] 0B
ADD alpine-minirootfs-3.20.10-x86_64.tar.gz … 8.47MBNeither image has a /blob.bin, yet the split one is 50 MB heavier to pull (CONTENT SIZE is what a pull downloads; DISK USAGE adds the unpacked copy). The rm layer weighs 4.1 kB: it is only the whiteout. Create and remove temporary files in the same RUN, or better, produce them in a build stage the final image never includes (the next lesson's lab).
05. How the build cache decides what to rerun
BuildKit, the builder behind docker build, keeps the result of every instruction. Before running one, it works out a cache key from the instruction's parent result, the instruction text (including any build arguments and environment it uses) and, for COPY and ADD, a checksum of the files being copied. A match means the step is reused and the build log says CACHED. A miss runs the step, and every later step in the same stage misses too, because its parent has changed. Four consequences follow:
- Order matters. Put what changes rarely (system packages, dependencies) before what changes often (your code), so an edit only reruns the last few steps.
- The cache does not look outside.
RUN apt-get updateis reused for as long as its text is unchanged, however old its package lists get. Rebuild with--pull --no-cacheon a schedule to pick up base image and package fixes. - Cache mounts keep downloads, not layers.
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txtkeeps pip's download cache between builds without putting it in the image, so a changed requirements file reinstalls without downloading everything again. - CI runners start cold. Each fresh runner has an empty cache. Export it to a registry and import it on the next run (
type=ghadoes the same through the GitHub Actions cache):
docker buildx build \
--cache-from type=registry,ref=registry.example.com/notes-api:buildcache \
--cache-to type=registry,ref=registry.example.com/notes-api:buildcache,mode=max \
-t registry.example.com/notes-api:1.4.0 --push .mode=max also exports the intermediate stages of a multi-stage build. The default builder can export cache when Engine uses the containerd image store; with the classic store, create a builder first with docker buildx create --use.
06. What not to bake into an image
Anything written into a layer goes to everyone who can pull the image, for as long as the image exists, even if a later layer deletes it. Keep these out:
- Secrets: tokens, passwords, private keys,
.envfiles. Build arguments are no hiding place: their values are recorded in the image history. - Large data and model weights: a 4 GB weights file in a layer makes every pull, push and cache miss move 4 GB and ties model updates to image rebuilds. Mount them at run time, or download them at start-up into a volume (for example
-v hf-cache:/models -e HF_HOME=/models). - Build tools and caches: compilers, header files, pip caches and test suites. A multi-stage build leaves them in a stage that is never shipped.
- Your machine's clutter:
.git,.venv,__pycache__, local databases. A.dockerignorekeeps them out of the build context and out of theCOPYchecksums. - Per-environment configuration: URLs, feature flags, log levels. Pass them as environment variables when the container starts (lesson 4), so one image runs in every environment.
See the difference between a build argument and a secret mount for a build-time token. Use a fake value, as here:
FROM alpine:3.24
ARG API_TOKEN
RUN echo "${#API_TOKEN}" > /token-lengthFROM alpine:3.24
RUN --mount=type=secret,id=api_token,env=API_TOKEN \
echo "${#API_TOKEN}" > /token-lengthdocker build -q --build-arg API_TOKEN=fake-123 -f Dockerfile.argleak -t leak:arg .
docker history leak:arg --no-trunc --format '{{.CreatedBy}}' | head -n 1
export API_TOKEN=fake-123
docker build -q --secret id=api_token,env=API_TOKEN \
-f Dockerfile.secret -t leak:secret .
docker history leak:secret --no-trunc --format '{{.CreatedBy}}' | head -n 1
docker run --rm leak:secret cat /token-lengthsha256:54239285d571cde0477b71329337d0d2952f8fe065eebf66d38be78cb2491b07
RUN |1 API_TOKEN=fake-123 /bin/sh -c echo "${#API_TOKEN}" > /token-length # buildkit
sha256:eb54cc7c72fcb7914bc8ab634b785c18bbfbd1490a0423438b91153050855e77
RUN /bin/sh -c echo "${#API_TOKEN}" > /token-length # buildkit
8The build argument's value sits in plain text in the history of leak:arg (a build without -q also warns SecretsUsedInArgOrEnv). The secret mount gave the token to that one RUN step only, and nothing of it reached the image, yet the step still saw all 8 characters.
07. Check your understanding
08. Apply it
Prepare the practice project for its Dockerfile, which you will write in the next lesson's lab:
- Choose a base image and record its tag and digest with
docker buildx imagetools inspect. Plan to pin it as shown above, with an automated update in your repository. - List everything in the project folder and mark each item: copy into the image, ignore, or provide at run time. Secrets,
.env, model weights and datasets belong in the last two groups. Turn the "ignore" group into a.dockerignore. - If the build needs a private package index or token, write the
RUN --mount=type=secretline now, and check withdocker history --no-truncthat the value never appears. - Draft the CI build step with
--cache-fromand--cache-to, and decide where the pushed digest will be recorded (release notes or a deployment file).
09. Review prompt
Without looking back, name the four kinds of object in an OCI image and say which one a digest from docker push identifies. Explain copy-up and whiteouts in your own words, and why deleting a file in a later RUN does not shrink an image. State the three inputs to a cache key for a COPY step, and list four things that should never be baked into an image, with where each should come from instead.
References
- OCI Image Format Specification
- Docker Docs: docker buildx imagetools inspect
- Docker Docs: Storage drivers
- Docker Docs: containerd image store with Docker Engine
- Docker Docs: Docker build cache
- Docker Docs: Build secrets
- Docker Docs: Build context and .dockerignore
- Docker Docs: Building best practices
- Docker Docs: Multi-stage builds
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.