In this lesson, you will learn how to shrink your Docker images by deleting temporary files created during the installation process.
The Hidden Cost of Installation
When you run a command like apt-get install or yum install, the package manager downloads thousands of files into a local cache directory. These files are essential for the installation to succeed, but they become completely useless the moment the installation finishes.
If you leave these files in your image, they persist in that layer forever. Even if you try to delete them in a subsequent RUN instruction, the files still exist in the previous layer, and the final image size will not decrease. To truly reclaim that space, you must delete the artifacts in the same layer where they were created.
The "Chained" Approach
Because each RUN instruction creates a new layer, you need to combine the installation and the cleanup into one command using the && operator.
Here is a common example using an Ubuntu-based image:
RUN apt-get update && apt-get install -y \
python3 \
curl \
&& rm -rf /var/lib/apt/lists/*
In this block:
apt-get updatefetches the package lists.apt-get install -y python3 curldownloads and installs the tools.rm -rf /var/lib/apt/lists/*deletes the massive cache of package lists.
By chaining these with &&, Docker treats them as a single atomic operation. The package cache is never "committed" to the final image as a standalone file; it is created and destroyed within the same temporary filesystem transaction. This keeps your image lean and prevents "bloat" from accumulating as you build your application.
Always look for these temporary folders—like /var/lib/apt/lists/, /tmp/*, or cache directories created by tools like npm or pip—and make sure to wipe them clean before the RUN command finishes.
Key Takeaway: To reduce your image footprint, always delete temporary build artifacts and package manager caches in the same RUN instruction where they were created.