Dockerfile: Consolidate Multiple RUN Instructions

Multiple RUN instructions create unnecessary image layers and slower builds. Combine related commands in one RUN line to reduce size and improve maintainability.

Problem

Multiple consecutive RUN instructions create extra layers and make the Dockerfile harder to maintain.

Description

Every RUN creates a new image layer. When related shell operations are split into many layers, images become larger and cache invalidation becomes less efficient. This increases build and distribution cost, especially in CI where images are rebuilt frequently.

Layer sprawl also makes troubleshooting harder. Reviewers must track logic across multiple blocks to understand one package workflow. Consolidating related commands with && keeps intent explicit and reduces the chance of leaving temporary files behind in intermediate layers.

Related rules: combine update and install in one RUN, clean package cache, use –no-install-recommends.

Solution

Combine consecutive RUN commands when they belong to the same operation. Keep commands readable, deterministic, and focused on producing minimal, reproducible image layers.

Problematic code

FROM ubuntu:20.04
RUN apt-get -y --no-install-recommends install netcat
RUN apt-get clean
USER nobody

Verified code

FROM ubuntu:20.04
RUN apt-get -y --no-install-recommends install netcat && apt-get clean
USER nobody

Source of the description

Dockerfile best practices