Quickly Cleaning Up Docker Images from the Command Line

One of the things I find quite annoying is cleaning up Docker images on a development machine, such as my laptop. Over time, they tend to accumulate as you experiment with things, clogging up your machine. It’s really handy to have a quick and easy way to get rid of them. As I typically work from the command line, I wanted a way to do it there, and so I created a shell alias that does it in combination with fzf.

Here it is:

alias docker-rmi-interactive="docker images | sed -E 's%([^[:space:]]+)[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]]+).*%\\1:\\2 \\3%g' | tail -n +2 | sort -r | fzf -d' ' -m --with-nth=1 | cut -d' ' -f2 | xargs -t docker image rm"

The sed command takes docker images with a separated name, version, and image ID and combines them together in the form namespace/imagename:version suitable for display to fzf, with fzf then passing the image ID to docker image rm. You can multi-select images from fzf using the <Tab> key; if you want to modify any of the fzf options you can of course take a look at its man page.

Hope it helps!