Review pip caches included in container images

Keep unnecessary pip caches out of the final image.

Description

pip can cache package downloads and the wheels it builds. These files can end up in the runtime image.

Potential impact

Shipping the cache increases image size. Disabling it everywhere can slow repeat builds.

Remediation

Use pip install --no-cache-dir for an install whose cache would ship in the image. To reuse downloads across builds, use a BuildKit cache mount outside the image. Check earlier layers for caches from previous installs.

Examples

Choose and update the required flask and requests versions 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

References