Review pip caches included in container images

Keep unnecessary pip caches out of the final image.

Description

pip install can cache downloaded responses and built wheels. When that cache is included in the final image, files unnecessary at runtime can increase image size.

Build caches reduce repeated downloads and build work. Keeping a cache outside the final image, such as through a BuildKit cache mount, can be appropriate.

Potential impact

  • Unnecessary caches can increase image size and storage or transfer costs.
  • Disabling all caching can increase repeated build time and network use.

Remediation

  • For ordinary installations that retain caches in image layers, use pip install --no-cache-dir or configure a build cache outside the final image.
  • Check whether caches are present in the final image. --no-cache-dir disables caching for that command; it does not delete caches from earlier layers.

Examples

The examples compare pip caching only. Manage version pins and update policies for flask and requests separately.

Before

dockerfile
FROM python:3.12-slim

RUN pip install flask requests

After

dockerfile
FROM python:3.12-slim

RUN pip install --no-cache-dir flask requests

Explanation:

  • Before: The default pip cache can be included in the image.
  • After: This installation does not use the pip cache. Check caches from other commands or earlier layers separately.

References