Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 94 of 8022. Docker Image LifecycleFree lesson

Optimizing Image Size Through Layer Management

You will apply techniques to minimize the number of layers in an image to improve build performance and reduce storage overhead.

In this lesson, you will learn how to reduce your Docker image footprint by strategically chaining commands to minimize the number of layers created during the build process.

The Problem: Every Instruction is a Layer

In Docker, every time you use an instruction like RUN, COPY, or ADD in your Dockerfile, Docker creates a new, immutable filesystem layer. If you run multiple commands separately, each one saves a new "snapshot" of the filesystem. This can lead to bloated images because even if you delete a file in a later layer, the original file still exists in the previous layer, consuming storage space.

The Solution: Combining Commands

To optimize your image size, you should combine related commands into a single RUN instruction using the && operator. This allows you to perform cleanup tasks (like removing cache files) in the same layer where they were created.

Consider this inefficient example:

RUN apt-get update
RUN apt-get install -y python3
RUN rm -rf /var/lib/apt/lists/*

In this scenario, three separate layers are created. Even though you remove the package lists in the third step, the data remains inside the first layer, wasting space.

Now, look at the optimized version:

RUN apt-get update && \
    apt-get install -y python3 && \
    rm -rf /var/lib/apt/lists/*

By chaining these commands, Docker executes them all within a single layer. The package lists are downloaded, used to install Python, and then deleted before that single layer is finalized. Because the deletion happens before the layer is committed, the temporary files are never saved to your final image, resulting in a much smaller total size.

By keeping layers "clean" and minimizing the number of instructions, you speed up your build process, reduce the amount of data transferred over the network, and save precious storage space on your container hosts.

Key Takeaway: Always chain related commands using && within a single RUN instruction to ensure temporary files are deleted before the layer is finalized.