Sub topic 7
Why deleting files in a later layer does not shrink the image
This chapter assumes you can read a Dockerfile, run docker build, and know that an image is made of stacked layers. It explains why a rm in a later step leaves the image size unchanged, how to confirm that, and the three standard ways to avoid it.
The problem in one example
A common first attempt at a small image downloads an archive, unpacks it, and deletes the archive. The Dockerfile below does that in separate steps.
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Two separate RUN steps: the archive stays stored in the first layer.
RUN curl -fsSLO https://example.com/big.tar.gz
RUN tar -xzf big.tar.gz -C /opt && rm big.tar.gzSuppose big.tar.gz is 400 MB and unpacks to 600 MB. A reader would expect the final image to hold roughly the 600 MB of unpacked files. It actually holds about 1 GB, because the 400 MB archive is still stored in the layer created by the curl step.
Why the size does not drop
Each RUN, COPY, and ADD instruction produces a layer. That layer is a record of the filesystem changes the step made. Once a layer is built, it is read-only and identified by a digest of its contents. A later instruction cannot reach back and edit it.
The rm in the last step therefore does not remove bytes from the earlier layer. It creates a new layer that marks the file as deleted. When a container starts, the layers are merged into one view, and the deletion marker hides the file in that view. The earlier layer still contains the archive, and the image still has to store and transfer it.
The image size is the sum of its layers, not the size of the merged view.
Whiteout files
Layers are stored as tar archives. To record a deletion, the builder adds a special entry called a whiteout. For a deleted file big.tar.gz, the entry is named .wh.big.tar.gz. For a deleted directory's contents, an opaque marker (.wh..wh..opq) is used. When the layers are merged, the filesystem driver reads these markers and hides the matching paths from lower layers.
This is why deletion adds a small amount of data instead of subtracting any.
The same applies to other changes
Deleting is not the only operation that grows an image without a visible effect. Any change to a file that already exists in a lower layer stores extra data.
| Operation in a later layer | What the new layer stores | Effect on image size |
|---|---|---|
| `rm` of a file | A whiteout entry | Tiny increase, no reduction |
| Overwriting a file | The full new file | Old and new copies both stored |
| `chmod` or `chown` of a file | A full copy of the file with new metadata | The whole file is stored again |
| `chown -R` on a large directory | Copies of every file in it | Size can nearly double |
The chown -R case is a frequent surprise. Changing ownership of a 500 MB directory in its own RUN step adds roughly another 500 MB layer. Prefer COPY --chown=user:group so the files are written once with the right owner.
Confirming it with docker history
You can see the problem directly. Build the image and list its steps with their sizes.
docker build -t myapp:dev .
docker history myapp:dev
docker image inspect --format '{{json .RootFS.Layers}}' myapp:devIn the docker history output, the step that ran curl shows a size near 400 MB. The step that ran tar ... && rm shows a size near 600 MB. The rm did not give any of the 400 MB back. The inspect command prints the digests of the filesystem layers, so you can count them and compare against the history rows.
Fix 1: delete in the same step that creates the file
A layer records the difference between the filesystem before and after one step. If a file is created and removed within the same RUN, it never exists at the end of that step, so the layer never contains it.
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL https://example.com/big.tar.gz | tar -xzf - -C /optThis version streams the download straight into tar, so the archive is never written to disk at all. If you need the file on disk, combine the steps with &&:
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSLO https://example.com/big.tar.gz \
&& tar -xzf big.tar.gz -C /opt \
&& rm big.tar.gzThe final layer holds only the unpacked files. The image is about 600 MB larger than the base, not 1 GB.
The same rule for package indexes
The package manager example from the spine follows the same logic. Running apt-get update, the install, and the cleanup in one RUN keeps the package index out of every layer:
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Keeping update and install together has a second benefit. If update were its own step, the build cache could reuse an old package index for months, and a later install could fail or fetch outdated versions. One combined step is cached or rebuilt as a unit.
Fix 2: use a multi-stage build
Chaining commands works when the cleanup is simple. It becomes awkward when the build needs compilers, headers, or source trees that you want to discard. A multi-stage build handles this by separating the build environment from the runtime image.
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The final image starts from distroless/static-debian12. The only thing it takes from the build stage is the compiled binary at /out/app. The Go toolchain, the module cache, and the source files stay in the build stage's layers, which are not part of the final image. Nothing needs to be deleted, because it was never copied in.
Multi-stage builds are covered in more detail in their own chapter. For this chapter, the point is that they avoid the deletion problem instead of working around it.
Fix 3: keep large files out of layers with mounts
BuildKit can make a file available to a single RUN step without storing it in a layer. A cache mount keeps a package manager's download cache between builds:
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
COPY . .The contents of /root/.cache/pip live outside the image. They are available during the step and are not committed to the layer. This removes the need for pip install --no-cache-dir and also speeds up rebuilds when requirements.txt changes. Cache mounts get a fuller treatment in a later chapter.
Choosing between the fixes
| Situation | Best approach |
|---|---|
| Temporary download or archive used by one step | Create and delete it in the same `RUN` |
| Package manager index or cache | Clean up in the same `RUN`, or use a cache mount |
| Compilers, build dependencies, source code | Multi-stage build |
| Files needing a specific owner or mode | `COPY --chown` or `COPY --chmod` |
| Secrets used during the build | A secret mount, never a file you delete later |
Edge cases and common mistakes
- Cleanup in a different step from the install.
RUN apt-get install ...followed byRUN rm -rf /var/lib/apt/lists/*saves nothing. The lists remain in the install layer. - Squashing as a workaround. Flattening an image into one layer does drop deleted files, but it also discards layer sharing and cache reuse. Fixing the Dockerfile is usually better.
- Chaining too much. Putting every command into one giant
RUNremoves the deletion problem but destroys caching granularity. A change to any part rebuilds the whole step. Group commands that belong together, such as download, unpack, and clean. - Deleting files that came from the base image. Removing files from
debian:bookworm-slimin your own step only adds whiteouts. The base layers are shared and unchanged. To get a smaller base, pick a smaller base image. - Mounted volumes are not layers. Data written to a path declared with
VOLUMEduring a later build step may be discarded, and it is not stored in the image the way regular files are.
Exercise
A Dockerfile has RUN wget https://example.com/data.zip, then RUN unzip data.zip -d /data, then RUN rm data.zip. The zip file is 200 MB. Explain why the final image is still at least 200 MB larger than needed, and rewrite the three steps so the image does not carry the zip.
Show answer
Each RUN creates its own layer. The wget layer stores data.zip permanently. The rm step only adds a whiteout entry in a new layer, which hides the file in the merged view but does not remove it from the earlier layer, so the image size still includes the 200 MB. Combine the steps so the file is created and deleted within one layer: RUN wget https://example.com/data.zip && unzip data.zip -d /data && rm data.zip. A multi-stage build that copies only /data into the final stage also works.
Exercise
You run docker history on an image. One step shows 0 B and its command is rm -rf /build-tmp. The step before it shows 350 MB. What does this tell you, and where would you look to fix it?
Show answer
The rm step only recorded whiteout entries, so it adds almost nothing, and the 350 MB step still stores the files that rm hid. The fix belongs in the earlier step: either remove the files within that same RUN command, or move the build into a separate stage and copy only the needed output into the final image.