Occasionally, I have needed to stop and remove all the docker containers I am running locally. I got tired of googling for the commands all the time and decided to write a snippet that I could access easily.
Before we see how to stop and remove all containers, we need to list all the containers.
The command to lists all containers is
docker container ls [OPTIONS].
By default, it shows just the running containers and a lot of information that we won’t need. So let’s pass in some options
- -a: Show all the containers.
- -q: Only display the numeric ids.
docker container ls -aq
The command to stop docker containers is
docker container stop [OPTIONS] CONTAINER [CONTAINER...]
We can see it takes a space-delimited list of container ids/names to stop. We already have the list of container ids from the previous step. All we need to do now is use a shell expansion trick to pass in the list of all containers.
docker container stop $(docker container ls -aq)
The command to remove docker containers is
docker container rm [OPTIONS] CONTAINER [CONTAINER...]
We can see it’s similar to the stop command and also takes a space-delimited list of container ids to remove.
We can use the same shell expansion trick to pass in the list of all containers.
docker container rm $(docker container ls -aq)
This makes it trivial to stop and remove all the containers that I have running locally.