Automated cleanup of Docker leavings

As much as I like Docker, one thing it doesn't do well: cleanup whatever is left on my hard drive after running it for a while. There're generally two kinds of Docker Waste:

  • Exited containers. Unless you used run --rm when running a new container from an image, docker doesn't automagically remove containers once they're stopped; you need to rm them explicitly. Since it's generally considered (at least, by me) a Docker good practice to never restart a container, they just stay there and take valuable disk space. Of course sometimes it's useful or even necessary not to start a container with --rm, because you may want to inspect the filesystem after exiting, but most of the times it's an oversight.
  • Dangling images. Whenever you build a brand-new Docker image with the same tag as an existing one, you'll be possibly left with an old, dangling image - i.e an image you can only use by tag, not by name. The same could happen when an upstream image changes. More or less just like a git dangling object. Small note: it doesn't necessarily happen. The new image can be a perfect child of the previous image, in that case Docker uses a kind of inheritance mechanism which produces no dangling images. But if the image changes "in the middle" of the Dockerfile, and hence a piece of the old image get invalidated, then you'll be left with some dangling images.

So, here's the script. Just put it in your /etc/cron.daily directory and live quite happily ever after:

#!/bin/bash
docker ps -a -q --filter="status=created" | xargs --no-run-if-empty \
docker rm
docker ps -a -q --filter="status=exited" | xargs --no-run-if-empty \
docker rm
docker images -q -f dangling=true | xargs --no-run-if-empty \
docker rmi