rspec/rules/S7031/docker/rule.adoc

67 lines
2.3 KiB
Plaintext

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
[source,docker,diff-id=1,diff-type=noncompliant]
----
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
[source,docker,diff-id=1,diff-type=compliant]
----
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
* Dockerfile Best Practices - https://github.com/dnaprawa/dockerfile-best-practices?tab=readme-ov-file#limit-image-layers-amount[Limit image layers amount]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Primary locations: Merge this `RUN` instruction with the consecutive ones.
Secondary locations: consecutive `RUN` instruction
=== Highlighting
Highlight only the keywords `RUN` of each consecutive instruction. The primary location is the first `RUN` instruction, and the secondary locations are the other one followings.
'''
== Comments And Links
(visible only on this page)
endif::env-github,rspecator-view[]