TL;DR
docker rm $(docker ps -a | grep Exited | cut -d " " -f 1)How it works
Recently, I forgot to include --rm when running a bunch of throwaway containers, so my system was cluttered with loads of stopped containers with auto-generated names.
Quickly create lots of throwaway containers:
Bashfor i in {1..10}; do docker run hello-world; doneReplace
10with the number of containers to create.
To remove stopped containers we need to invoke docker rm CONTAINER, where CONTAINER is repeatable and can be either a container’s name or id.
The command docker ps -a lists all existing containers and their ids. We can select the rows for stopped containers with grep Exited. Then we can extract the container id with cut -d " " -f 1 which splits the row on spaces (the “delimiter”) then chooses the first column (1-indexed).
docker ps -a | grep Exited | cut -d " " -f 1We can pass the output of that command to docker rm as a shell expansion
docker rm $(docker ps -a | grep Exited | cut -d " " -f 1)And just like that all your stopped Docker containers will be removed!