Multiplying the number of RUN instructions increases the final image build time and size.

Why is this an issue?

Each time a RUN instruction is added, a new layer is introduced in the final image.
This has a direct impact on the build time and image size. Chaining commands in a single RUN instruction using && will use a single layer, thereby reducing the number of layers in the image.
This practice can make Docker images more efficient and easier to manage.
Each layer in a Docker image is essentially a change to the image, like a version control system.
So, fewer layers mean fewer changes to track, which simplifies management and troubleshooting.

Exceptions

In multi-stage builds, the rule only scans instructions that are part of the final image.

How to fix it

Code examples

Noncompliant code example

RUN curl -SL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.gz" --output nodejs.tar.gz
RUN echo "$NODE_DOWNLOAD_SHA nodejs.tar.gz" | sha256sum -c -
RUN tar -xzf "nodejs.tar.gz" -C /usr/local --strip-components=1
RUN rm nodejs.tar.gz
RUN ln -s /usr/local/bin/node /usr/local/bin/nodejs

Compliant solution

RUN curl -SL "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.gz" --output nodejs.tar.gz \
&& echo "$NODE_DOWNLOAD_SHA nodejs.tar.gz" | sha256sum -c - \
&& tar -xzf "nodejs.tar.gz" -C /usr/local --strip-components=1 \
&& rm nodejs.tar.gz \
&& ln -s /usr/local/bin/node /usr/local/bin/nodejs

Resources

Documentation