Docker cookbook · Intermediate
Shrink a bloated image
An image is over 1 GB; make it smaller without breaking it.
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
- Add a healthcheck to an HTTP service
- Build a layered image for a Spring Boot app
- Build a production image for a Node.js service
- Build a production image for a Python web app
- Build, cache and push images in GitHub Actions
- Build one image tag for amd64 and arm64
- Configure nginx from environment variables
- Develop with Compose and live reload