Remove Docker containers by tag

24 Mar 2022 in TIL

I always forget to pass the --rm flag when running command line tools with Docker. This means that I end up with a large history of exited containers that I no longer need.

There's plenty of information out there about how to clean up all stopped containers, or all unused images. I wanted to delete all stopped containers with a specific tag. Here's how to do it:

bash
docker rm $(docker container ls -a -q --filter ancestor=image-name:tag --filter status=exited)

This works thanks to the filtering capabilities when combined with the -q option to output only container IDs. These are then fed in to docker rm to remove all images with that tag that are in the exited status.