- https://towardsdatascience.com/fast-docker-builds-with-caching-for-python-533ddc3b0057/
- Type: article
- Source: Towards Data Science · Jan Michelfeit · Dec 2021
TL;DR
Cache the dependency layer, build in two stages and pass credentials as BuildKit secrets, so Docker rebuilds only what changed, even in CI.
Summary
Python image builds are slow because dependency installation reruns, CI systems offer little layer cache and private package indexes need credentials. The article copies dependency manifests (pyproject.toml, lock file) and installs before copying code, so that layer is rebuilt only when dependencies change. A build stage creates a virtualenv, the slim final stage copies it, and secrets are mounted at build time so they do not invalidate the cache.
Key takeaways
- Separate the dependency layer from application code.
- Use multi-stage builds: build stage for dependencies,
3.8-slimfor the final image. - Exclude dev dependencies (
poetry install --no-dev) to shrink the image. - Copy the venv between stages and set
PATHandVIRTUAL_ENV. - Pass credentials with
--secret(DOCKER_BUILDKIT=1); mounts are ignored by caching logic. - Warm CI caches by building
--target build-stageand listing it andlatestas cache sources, or move them withdocker save. - Harden: run as non-root and set
PIP_NO_CACHE_DIR=1in the build stage.
Tools and concepts
| Item | Role in the page |
|---|---|
| Docker | Layer cache, BuildKit secrets |
| Python | Poetry-based dependency management |
| DevOps | CI/CD cache reuse |
When to use
- When speeding up Python Docker builds in CI.
- When you need to inject private-index credentials without baking them in layers.
- When reducing final image size with multi-stage builds.
Caveats
- The Dockerfile and CI snippets were not captured, and the article reports no timings.
Docker Python DevOps Using YAML Anchors and X Properties in Docker Compose