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.
More on Kubernetes, Docker & SSH clients
How does the official Kubernetes Python client authenticate?BeginnerHow do you list pods with high restart counts using the Python client?BeginnerHow do you patch or scale a Deployment with the Python client?IntermediateHow does `watch.Watch()` work, and what is a `410 Gone`?AdvancedHow do you apply a YAML manifest from Python?AdvancedHow do you use the Docker SDK for Python?Beginner