loading...

How to stop and remove all Docker containers

ankursheel profile image Ankur Sheel Originally published at ankursheel.com on ・2 min read

Problem

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.

Solution

Before we see how to stop and remove all containers, we need to list all the containers.

List all Containers

The command to lists all containers isdocker 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

Stopping all containers

The command to stop docker containers isdocker 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)

Removing all containers

The command to remove docker containers isdocker 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)

Conclusion

This makes it trivial to stop and remove all the containers that I have running locally.

Discussion

markdown guide