Why do Dockerfiles chain commands with && in one RUN instruction?
Each RUN creates a layer, and deleting files in a later layer does not shrink the image. Chaining install and cleanup in one RUN means the temporary files never get stored in any layer.
Explain it simply
Layers are like photographs stacked in an album. If you take a photo of a messy room and then another photo of the clean room, the album still contains the messy photo. To keep it out, you must clean before taking the picture.
With RUN apt-get update then RUN apt-get install -y curl then RUN rm -rf /var/lib/apt/lists/*, the package lists are stored in the first two layers and the third only hides them, so the image stays large. Putting everything in one RUN with && means the lists are removed before the layer is saved. It also keeps apt-get update and install together, which avoids a stale cached update layer.
Do not over-chain unrelated steps, though: a single huge RUN loses caching granularity. Group by purpose.
Example
# bad: three layers, cache files kept
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# good: one layer, nothing left behind
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*What to say in the interview
"Each RUN adds a layer, and later deletions do not shrink earlier layers. I chain update, install and cleanup in one RUN so temporary files are never stored, while keeping unrelated steps separate for caching."
Common mistakes
- Running apt-get update in its own RUN, which gets cached and goes stale.