Signup/Sign In

How to remove or delete a Docker Containers?

If you work with docker and keep on creating containers to test different setups and find it difficult to handle all the unnecessary docker containers created during the development process, then in this tutorial, you will learn how to remove unwanted docker containers using docker commands.

Remove a specific Docker container

If you want to remove a specific docker container then you will have to find the container and then remove it.

To list down all the containers you can use the following command:

docker ps -a

docker container list

Once you have the list of the docker containers, you can use the docker rm command to remove one or more docker containers.

For example,

docker rm f1259a8dbcc2

or, you can use the name of the container,

docker rm welcome-to-docker

You can remove more than one container together by specifying the names or IDs of all the containers (space separated) in one docker rm command.

docker rm ContainerID1 ContainerID2 ContainerID3

Remove a container when it exits

If you are creating a container just to test something and you would want the container to be deleted as soon as the container exits, then you can run the docker container using the docker run command along with --rm flag, like this,

docker run --rm DOCKER_IMAGE

Remove Docker containers using a pattern

If you name similar docker containers following some pattern then you can also remove all those docker containers by running a single command.

To list down all the docker containers with a name that follows a pattern, you can use the following command:

docker ps -a | grep "some-pattern”

This will list down all the containers with names containing the "some-pattern" string. You can change this to any string value that you want to search for.

Once you have listed all the docker containers and you are satisfied with the result, then you can use the following command to remove all of those docker containers,

docker ps -a | grep "some-pattern" | awk '{print $1}' | xargs docker rm

In the above command, we have used two docker commands - docker ps and docker rm, along with two Linux commands - grep and awk.

We hope this tutorial helped you in learning docker commands to manage your docker containers and remove the docker containers that you don't need anymore.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight