In good old days, we used to write scripts to cleanup stale Docker containers, images, volumes, etc. Docker Engine 1.25 provided a welcome change on this. Now, there's a relatively straightforward way to cleanup unused resources using the following command.
docker system prune
With this single command, you can remove all stopped containers, unused networks, dangling images, and build cache.
Even more importantly,
prune is also available for other resource commands.
docker container prune # removes all stopped containers docker image prune # removes unused images docker network prune # removes all unused networks docker volume prune # removes all unused local volumes docker builder prune # removes build cache
There are also a couple of useful flags available:
-aremoves all unused images and build cache (not merely dangling ones)
--filterprovides filtering capabilities by label or timestamp. (e.g.,
--filter "until=24h"). You can pass multiple filters.
-fexecutes the command without any confirmation prompt