4.3.2.3 Package Cache Cleanup
A focused guide to Package Cache Cleanup, connecting core concepts with practical Docker and container operations.
Package cache cleanup is the practice of removing a package manager's downloaded package index or cached files within the same RUN instruction that installed packages, preventing that cached data from permanently adding to the image's size in a layer that a later cleanup step could not actually shrink.
Why Cleanup Must Happen in the Same Instruction
Because each RUN instruction's layer permanently captures filesystem state at that point, deleting cache files in a separate, later instruction does not reduce the image's size — the cached data still exists, unmodified, in the earlier layer.
RUN apt-get update && apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
The second version, combining installation and cleanup into one instruction, produces a layer reflecting only the net, cleaned-up result.
Cleanup Patterns for Common Package Managers
Different package managers store their cache and index data in different locations, each requiring its own specific cleanup command.
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
RUN apk add --no-cache curl
Alpine's apk supports a --no-cache flag that avoids storing the cache in the first place, eliminating the need for an explicit cleanup step entirely.
RUN pip install --no-cache-dir -r requirements.txt
Many language-specific package managers similarly support a flag to disable caching during installation, which is generally preferable to installing with caching enabled and cleaning up afterward.
Measuring the Effect of Cleanup
Comparing image size with and without proper cache cleanup demonstrates the concrete savings this technique provides, which can be substantial depending on how much was downloaded during installation.
docker history myapp:1.0
Why Package Cache Cleanup Matters
This single, easily overlooked detail is one of the most common reasons images end up larger than necessary — package manager caches can add a surprising amount of unnecessary size if not addressed within the same layer that created them.