Review apt-get package-list cleanup

Install packages and remove their package lists in the same RUN instruction.

Description

Package lists downloaded by apt-get update remain under /var/lib/apt/lists. Keeping lists that are unnecessary at runtime can increase image size.

This is an image-optimization and operational-efficiency issue. Deleting files in a later RUN does not shrink earlier layers, so complete installation and cleanup within the same layer.

Potential impact

  • Unnecessary package lists can increase storage usage and image-transfer time.
  • Cleanup in a separate layer may not deliver the expected size reduction.

Remediation

  • Run rm -rf /var/lib/apt/lists/* after apt-get install in the same RUN instruction.
  • Distinguish list removal from apt-get clean, which removes downloaded package archives. Refresh indexes again if later steps need to install more packages.

Examples

The examples compare package-list cleanup after installation. Maintain package-version management and security updates separately.

Before

dockerfile
FROM ubuntu:24.04

RUN apt-get update \
    && apt-get install -y --no-install-recommends python3

After

dockerfile
FROM ubuntu:24.04

RUN apt-get update \
    && apt-get install -y --no-install-recommends python3 \
    && rm -rf /var/lib/apt/lists/*

Explanation:

  • Before: The package lists used for installation remain in the layer.
  • After: After installation succeeds, the same RUN removes the lists so they do not remain unnecessarily in the resulting layer.

References