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

Minimizing Layers via Instruction Chaining

Combine multiple commands into single RUN instructions using shell operators to reduce the total number of layers and overall image size.

Minimizing Layers via Instruction Chaining

In this lesson, you will learn how to combine multiple commands into a single RUN instruction to shrink your final image size and reduce the number of layers.

Why Layers Matter

As you’ve learned, every RUN, COPY, and ADD instruction in your Dockerfile creates a new, immutable layer. If you run three separate commands to update your package manager, install a tool, and clean up temporary files, Docker creates three distinct layers. Even if you delete files in the third layer, they still exist in the previous two, meaning your image size doesn't actually decrease—it just grows larger with the "delete" instruction recorded.

The Power of Chaining

To solve this, we use shell operators (like &&) to chain commands together. By grouping commands into a single RUN instruction, they are executed as one atomic step. This ensures that any temporary files created and then deleted within that same layer don't persist in the final image.

Consider this inefficient approach:

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

This creates three layers. The third layer effectively "hides" the package lists, but the data remains stored in the first two layers.

Now, look at the optimized version using chaining:

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

By using &&, the commands run sequentially. Because they are part of one RUN instruction, the temporary apt files are created and deleted within a single layer. Docker only commits the end result of that entire chain, resulting in a significantly smaller image. Using the backslash \ allows you to keep your Dockerfile readable by breaking the long line into multiple visual lines while keeping it a single instruction to the Docker engine.

Key Takeaway: Combine related setup and cleanup commands into a single RUN instruction using && to prevent unnecessary data from bloating your image layers.