Skip to content

minimize-layers

Too many RUN instructions bloat Docker images. When and how to combine consecutive RUN commands with && to reduce layers.

On this page

Every RUN instruction commits a layer, and a layer only ever adds bytes — files deleted in a later layer are hidden, not removed. A Dockerfile written as a long list of small RUN steps accumulates layers (and often stray intermediate files) that the final image drags around forever. This rule flags runs of consecutive RUN instructions that could be one.

What the rule catches

Dockerfile — cleanup in a later layer removes nothing
FROM debian:12-slim
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*

Scanning this file reports:

ℹ INFO [docker-doctor/minimize-layers]
  Found 3 consecutive RUN instructions starting at line 2. Consider combining them into a single RUN layer.

Why it matters

The classic trap is cleanup in a separate step: RUN apt-get install … followed by RUN rm -rf /var/lib/apt/lists/* removes nothing from the image — the files are already committed in the earlier layer, and the rm just masks them. Combining related commands into a single RUN means temporary files can be created and deleted inside one layer, and the image only keeps the end state. Fewer layers also means less metadata overhead and faster extraction on pull.

How to fix it

Combine consecutive RUN instructions using && and \ to reduce the total layer count and image size.

Dockerfile — install and cleanup share one layer
FROM debian:12-slim
RUN apt-get update \
  && apt-get install -y --no-install-recommends curl \
  && rm -rf /var/lib/apt/lists/*

Don't over-correct into one giant RUN for the whole Dockerfile — that destroys build caching, because any change reruns everything. Group commands that belong to one logical step (install + cleanup, download + verify + extract), and keep steps that change at different rates in separate layers so the cache can work. See order-layers for the ordering half of this trade-off.

Rule details

  • Rule keydocker-doctor/minimize-layers
  • Category — Performance
  • Default severityinfo
  • Applies to — Dockerfiles

Explain this rule from the CLI:

npx @docker-doctor/cli@latest rules explain docker-doctor/minimize-layers

Change its severity — or turn it off — in your config file:

// docker-doctor.config.ts
export default {
  rules: {
    "docker-doctor/minimize-layers": "off",
  },
};

Severity affects the health score: error findings cost more points than warning, and info costs the least.