Dockerfile: Use –no-install-recommends with apt-get

Without --no-install-recommends, apt-get installs extra packages and larger images. Use the flag to keep dependencies minimal and auditable.

Problem

Without --no-install-recommends, apt-get installs extra packages that increase image size and CVE surface. Action: install only explicit dependencies and clean package index files in the same layer.

Description

Production images should contain only runtime essentials. Recommended packages add patch overhead and scanner noise across every release. Action: make minimal dependency selection a mandatory code review check.

Recommendation graphs can change between package repository updates, which introduces build drift even when Dockerfile text does not change. Action: monitor image size and installed package count in CI and alert on unexpected growth.

Use the deterministic one-layer pattern: apt-get update, apt-get install -y --no-install-recommends, then cleanup of /var/lib/apt/lists/*. Action: fail builds that split update and install across different layers for production images.

Use this rollout checklist for reliable package hygiene:

  • Require --no-install-recommends on all apt-get install commands.
  • Add explicitly named packages when a recommended dependency is truly needed.
  • Document why each non-obvious package is required for runtime.
  • Track image size and package-count deltas on every pull request.

Treat verification as part of the rule, not optional cleanup. Action: automate a static check, a build check, and a runtime smoke check in the default CI pipeline so regressions are caught before review.

  • Static check: fail when the disallowed pattern appears in Dockerfile or manifest.
  • Build check: run a minimal image build to confirm the secure pattern is valid.
  • Runtime check: start the workload and assert expected behavior with one deterministic probe.

Examples of code

Problematic code

FROM ubuntu:24.04
RUN apt-get update && apt-get install -y build-essential curl

Verified code

FROM ubuntu:24.04
RUN apt-get update && apt-get install -y --no-install-recommends build-essential curl && rm -rf /var/lib/apt/lists/*

Related rules