Docker cookbook · Intermediate

Shrink a bloated image

An image is over 1 GB; make it smaller without breaking it.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Find what's big (docker history, dive), then: switch to a slim or distroless base, use multi-stage builds, clean package caches in the same RUN, exclude junk with .dockerignore, and install only runtime dependencies.

Solution

FROM python:3.14-slim
RUN apt-get update && \
    apt-get install -y --no-install-recommends libpq5 && \
    rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY src/ ./src/
CMD ["python", "-m", "src"]
docker history --format '{{.Size}}\t{{.CreatedBy}}' app:dev | sort -rh | head

Pitfalls

  • Cleaning up in a separate RUN: deleted files remain in the earlier layer.
  • Installing build tools (gcc, headers) in the runtime image.
  • Removing things the app needs at run time (CA certificates, time zone data).

Variations

  • Multi-stage builds that compile wheels or binaries in a builder stage.
  • Docker Scout or dive to explore layers interactively.

Further reading: Dockerfile best practices

Reference: https://docs.docker.com/build/building/best-practices/

More Docker recipes

Was this page helpful?