In this lesson, you will learn how to prune unnecessary build files to keep your final Docker images lean, secure, and production-ready.
When you compile code inside a Dockerfile—such as installing development headers, downloading source code repositories, or generating object files (.o, .a)—these files consume valuable space in your image layers. Even if you delete them in a later instruction, the files still exist in the image's history because each instruction creates a new layer that persists the state of the filesystem.
To clean up these artifacts, you must remove them within the same RUN instruction where they were created. By chaining commands using && and finishing with a removal command, you prevent the temporary files from being "committed" to the layer’s history.
The Cleanup Pattern
Consider a scenario where you are installing a C++ library that requires source code to build. If you simply install and then remove in two separate RUN steps, the size of the source code remains burned into your image forever. Instead, combine them:
# WRONG: Creates a bloated layer
RUN apt-get update && apt-get install -y build-essential
RUN git clone https://github.com/example/repo.git
RUN cd repo && make && make install
RUN rm -rf /repo
# RIGHT: Cleans up artifacts in the same layer
RUN apt-get update && apt-get install -y build-essential \
&& git clone https://github.com/example/repo.git \
&& cd repo && make && make install \
&& cd / && rm -rf /repo \
&& apt-get purge -y build-essential \
&& apt-get autoremove -y \
&& rm -rf /var/lib/apt/lists/*
In the "Right" example, the rm -rf /repo and the cleanup of package manager caches (/var/lib/apt/lists/*) happen in the same layer as the build itself. When Docker creates the layer, it sees the final result—the installed binary—without the bulky temporary files that were created and deleted during the process. This keeps your image size significantly smaller and hides your build-time source code from potential attackers who might inspect your image.
Key Takeaway: Always delete your intermediate build artifacts in the same RUN command that creates them to prevent bloat and keep your images lean.