Removing stopped Docker containers

2 min read
Published Updated

TL;DR

Bash
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:

Bash
for i in {1..10}; do docker run hello-world; done

Replace 10 with 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).

Bash
docker ps -a | grep Exited | cut -d " " -f 1
Lists the IDs of all stopped containers

We can pass the output of that command to docker rm as a shell expansion

Bash
docker rm $(docker ps -a | grep Exited | cut -d " " -f 1)
Removes all stopped containers

And just like that all your stopped Docker containers will be removed!