Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 3

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

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:

  1. An index lists one manifest per platform, such as linux/amd64 and linux/arm64. This is what lets one name serve laptops and servers with different CPUs.
  2. A manifest describes one platform's image: one config and an ordered list of layers, each with its digest and size.
  3. The config holds the runtime defaults (environment, user, working directory, CMD and ENTRYPOINT, exposed ports, health check), the build history, and the digest of each uncompressed layer.
  4. 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:

Terminal
docker buildx imagetools inspect python:3.12-slim | head -n 8
Illustrative output (the second digest is shortened with …; digests change on every upstream rebuild)
Name:      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/amd64

Without 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:

Terminal
docker image inspect python:3.12-slim \
  --format '{{.Os}}/{{.Architecture}} cmd={{.Config.Cmd}} layers={{len .RootFS.Layers}}'
Expected output on an amd64 (x86-64) machine; on arm64, such as Apple silicon, the first field reads linux/arm64
linux/amd64 cmd=[python3] layers=4

03. Tags move, digests do not

A tag such as 3.12-slim is a pointer that the publisher moves. On the day these outputs were recorded it pointed at Python 3.12.15 on Debian trixie; next month it will point at a newer patch release. A digest names the content itself. To watch the difference, run a throwaway registry on your machine, push two builds under the same tag and keep the digest of the first:

Terminal
docker run -d --name ctr-registry -p 127.0.0.1:5000:5000 registry:3
printf 'FROM alpine:3.24\nRUN echo v1 > /version\n' \
  | docker build -q -t localhost:5000/demo:latest -
docker push -q localhost:5000/demo:latest
OLD=$(docker image inspect localhost:5000/demo:latest \
  --format '{{index .RepoDigests 0}}')
echo "${OLD#*@}"
printf 'FROM alpine:3.24\nRUN echo v2 > /version\n' \
  | docker build -q -t localhost:5000/demo:latest -
docker push -q localhost:5000/demo:latest
docker run --rm -q "$OLD" cat /version
docker run --rm -q --pull always localhost:5000/demo:latest cat /version
Illustrative output (all IDs and digests differ on your machine; registry:3 is pulled first)
e99d41e1f8230e0f24096ba68a326df78df84fa74ce8e39acc8a70cc395561eb
sha256:c194539b0f807a222295eab408d7ff277fc96d396a89bc9850143c9b10dc4ad0
localhost:5000/demo:latest
sha256:c194539b0f807a222295eab408d7ff277fc96d396a89bc9850143c9b10dc4ad0
sha256:52f661c86c3e8e406997c7ba893154e0ff0bfb00decc370a3fa5d56417b4ae57
localhost:5000/demo:latest
v1
v2

The tag latest now resolves to the second build, but the first digest still fetches exactly the first build. (With the containerd image store, the ID that docker build prints is the same digest the registry reports.) To pin a base image, keep the tag for readers and write the digest literally in FROM, where Renovate and Dependabot can bump it; one hidden in a build argument may never be updated.

Dockerfile (pinned base image: the alpine:3.24 index digest as of October 2026)
FROM alpine:3.24@sha256:be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a

Pinning trades freshness for repeatability: a pinned base gets no security fixes until you bump the digest. Remove the registry when you are done: docker rm -f -v ctr-registry.

04. 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:

Terminal
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-diff
Expected output (the order of the diff lines can differ)
C /tmp
A /tmp/note.txt
C /etc
C /etc/profile
D /etc/motd
ctr-diff

A 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:

Dockerfile.split
FROM alpine:3.24
RUN head -c 50000000 /dev/urandom > /blob.bin
RUN rm /blob.bin
Dockerfile.joined
FROM alpine:3.24
RUN head -c 50000000 /dev/urandom > /blob.bin && rm /blob.bin
Terminal
docker 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}}'
Illustrative output (recorded with the earlier alpine:3.20 base; IDs differ, and with 3.24 the last line names alpine-minirootfs-3.24.x and the base sizes differ slightly)
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.47MB

Neither 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 update is reused for as long as its text is unchanged, however old its package lists get. Rebuild with --pull --no-cache on 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.txt keeps 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=gha does the same through the GitHub Actions cache):
CI step (illustrative registry name)
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, .env files. 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 .dockerignore keeps them out of the build context and out of the COPY checksums.
  • 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:

Dockerfile.argleak
FROM alpine:3.24
ARG API_TOKEN
RUN echo "${#API_TOKEN}" > /token-length
Dockerfile.secret
FROM alpine:3.24
RUN --mount=type=secret,id=api_token,env=API_TOKEN \
    echo "${#API_TOKEN}" > /token-length
Terminal
docker 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-length
Illustrative output (image IDs differ)
sha256: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
8

The 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

Practice check · 3 questions

Check your image model

Use what the commands in this lesson showed.

Q1. A Dockerfile downloads a 50 MB archive in one RUN step and deletes it in the next RUN step. What happens to the image size?
Q2. A teammate passes a registry token with --build-arg and uses it in a RUN step. Who can read the token afterwards?
Q3. Without pulling anything, you want to see which platforms python:3.12-slim offers and the digest of each. Which command does that?
Practice only: not graded, not saved, not evidence.

08. Apply it

Prepare the practice project for its Dockerfile, which you will write in the next lesson's lab:

  1. 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.
  2. 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.
  3. If the build needs a private package index or token, write the RUN --mount=type=secret line now, and check with docker history --no-trunc that the value never appears.
  4. Draft the CI build step with --cache-from and --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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check