Interview Prep/Python for DevOps/Kubernetes, Docker & SSH clients

How do you clean up dangling Docker images and stopped containers with Python?

IntermediateConceptKubernetes, Docker & SSH clients
Answer
dc = docker.from_env()
dc.containers.prune(filters={"until": "24h"})
freed = dc.images.prune(filters={"dangling": True})["SpaceReclaimed"]
dc.volumes.prune()          # careful: removes unused volumes, which may hold data
log.info("reclaimed %.1f MB", freed / 1e6)

This maps to the Engine API prune endpoints, the same thing docker system prune uses. We run this on CI runners on a schedule; never on hosts where unused volumes may still hold data.

All Python for DevOps questions Roadmap: Python for automation

More on Kubernetes, Docker & SSH clients