Combining RUN Commands
What you'll learn: How to chain multiple shell commands into a single RUN instruction to reduce Docker image layers and overall size.
The Core Idea
Every RUN instruction in a Dockerfile creates a new layer in your image. If you have five separate RUN commands, you create five layers—even if later commands delete files created by earlier ones! Those deleted files still exist in previous layers, bloating your image.
The solution? Chain related commands together using && (the shell's "and" operator) in a single RUN instruction.
How It Works
Instead of writing:
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
Combine them:
RUN apt-get update && \
apt-get install -y curl && \
rm -rf /var/lib/apt/lists/*
This creates one layer instead of three. More importantly, when you delete the package cache in the same layer, those temporary files never get committed to the image—saving space.
The Cleanup Pattern
Think of layers like transparent sheets stacked on top of each other. If sheet 1 adds a 100MB file and sheet 2 deletes it, you still carry 100MB in the final image. But if you add and delete in the same sheet, the 100MB never becomes permanent.
Always clean up temporary files, caches, and build artifacts in the same RUN command that creates them.
Practical Tips
- Use
\for line continuation to keep commands readable - Chain with
&&so the entire command fails if any step fails - Common cleanups: package caches, temp files, build dependencies
Key Takeaway: Combine related RUN commands with && and perform cleanup in the same instruction to create fewer, leaner layers and significantly reduce image size.