Docker Image Layers and Caching Explained
You change one word in app.py, rebuild, and wait while pip downloads Flask all over again, though a teammate's similar app rebuilds in seconds. The difference comes from Docker image layers and the build cache. This lesson explains what layers are, how Docker reuses them, and how to order and trim a Dockerfile for fast rebuilds and small images.
An image is a stack of read-only layers
A layer is the set of file changes made by one build step: files added, changed or deleted. An image is an ordered stack of layers plus a small configuration file of settings, such as the start command. Each layer is read-only: once built, it never changes, and it is identified by its digest, the content fingerprint from Dockerfile Basics.
Only instructions that change files add a layer: RUN, COPY and ADD (a COPY that can also fetch URLs and unpack archives). FROM brings in the base image's layers. Settings such as USER, EXPOSE and CMD only change the configuration.
Starting a container adds one thin writable layer on top. Docker merges all the layers into one view, so the container sees one ordinary filesystem; where two layers hold the same path, the upper one wins. Whatever the app writes, such as logs, lands in the writable layer.
If the app edits a file from the image, Docker first copies it up into the writable layer and edits the copy, leaving the image untouched. This is copy-on-write. Deleting an image file only hides it. docker rm deletes the writable layer with the container; keeping data in volumes comes later, in Docker Volumes and Networking.
The diagram shows lesson 3's image, simplified. Notice that every file the container sees comes from exactly one sheet.
Layers are shared between images
Because layers are identified by digest, Docker stores each distinct layer once. Ten images built FROM python:3.12-slim download and store the base's layers once, and each adds only its own layers on top; docker pull skips layers you already have. The catch: they must use the same base version. The 3.12-slim tag moves with patch releases, so images built months apart may sit on different base layers.
Containers share too: ten containers from myapp use one copy of its image layers, each adding only its own writable layer, which starts empty.
How the build cache decides
The build cache is Docker's store of layers from earlier builds. BuildKit, the default builder in Docker Desktop and Docker Engine, walks your Dockerfile top to bottom, looking for a cached layer made by the same instruction on top of the same layers. Finding one is a cache hit, and the step is skipped; otherwise it is a cache miss, and the step runs.
For RUN, Docker compares only the command text: it does not rerun apt-get update to check for newer packages. For COPY and ADD, it compares a checksum, a fingerprint, of the copied files, so editing one character is a change, while a new modification time alone is not.
The key rule: after one miss, every later step is rebuilt without further checks, even if it would produce the same files, because each layer records changes on top of the exact layers beneath it. The flowchart follows one build.
Order your Dockerfile for fast rebuilds
So put steps that rarely change near the top and steps that change often near the bottom. Your code changes many times a day; your dependencies rarely do. This variant of lesson 3's Dockerfile gets it wrong, because it copies everything before installing:
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["python", "app.py"]
Every edit to app.py changes what COPY . . copies, so that step misses and pip install downloads Flask again, though requirements.txt did not change. Lesson 3's Dockerfile copies requirements.txt alone, installs, then copies the rest. The diagram compares both after the same edit.
To see it yourself, open a terminal in lesson 3's myapp folder, whose Dockerfile uses the good order. Build it once, then change the message in app.py, save, and build again:
docker build -t myapp .
The second build should mark the first steps as CACHED (trimmed, timings removed):
=> CACHED [2/6] WORKDIR /app
=> CACHED [3/6] COPY requirements.txt .
=> CACHED [4/6] RUN pip install --no-cache-dir -r requirements.txt
=> [5/6] COPY . .
=> [6/6] RUN useradd --create-home appuser
Steps 5 and 6 rerun because they follow the change, even though useradd gives the same result. If COPY . . misses when you changed no code, some file, such as a log, changes on every run; list it in .dockerignore. If pip install reruns after every code edit, check the order of your COPY lines.
Make images smaller
A smaller image downloads faster and gives attackers less to work with. First, a later layer can hide a file but never remove it from the layer that created it. So clean up in the same RUN step, joining commands with &&, which runs the next command only if the previous one succeeded. For example, to add curl with apt-get, Debian's package manager:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
apt-get update downloads package lists, --no-install-recommends skips optional extras, and rm deletes the lists before the layer is saved. As three RUN lines, the lists would stay in the first layer, and that cached update would serve stale lists later. In a real project, also pin the package version.
Second, start from a slim base, as Dockerfile Basics advised: python:3.12-slim leaves out the compilers and tools of the full python:3.12 image.
Third, use a multi-stage build: several FROM lines in one Dockerfile, each starting a new stage, of which only the last becomes your image. You compile in a big stage with all the tools, then copy just the result into a small one. Here a Go program, which compiles to a single file, is built in the official golang image:
FROM golang:1.24 AS build
WORKDIR /src
COPY main.go .
RUN go build -o /bin/hello ./main.go
FROM scratch
COPY --from=build /bin/hello /bin/hello
CMD ["/bin/hello"]
AS build names the stage for COPY --from=build. scratch is Docker's special, empty starting point, so the final image holds only the compiled program; the Go toolchain stays behind in the build stage.
Check yourself
An earlier RUN step downloads 200 MB into /tmp/downloads. You add RUN rm -rf /tmp/downloads as a new last line. Does the image get smaller?
No. The files stay in the earlier, read-only layer, and the new layer only hides them; delete them in the same RUN step that downloaded them.
You add a new package to requirements.txt and rebuild lesson 3's image. Which steps run again?
COPY requirements.txt and every step after it: its file's checksum changed, and after one miss every later step is rebuilt. FROM and WORKDIR stay cached.
Two containers run from the same myapp image, and one writes a 50 MB file to /tmp. Does the other container see it, and does the image grow?
Neither. The file goes into that container's own writable layer; the image layers both containers share are read-only, so nothing else changes.