How to use docker container rm command to remove containers

DockerDockerBeginner
Practice Now

Introduction

In this lab, you will learn how to effectively manage Docker containers by using the docker container rm command. You will practice creating and removing a basic container, understand how to force-remove a running container, explore the option of removing a container along with its associated anonymous volumes, and finally, learn how to efficiently remove all stopped containers.

Through hands-on exercises, you will gain practical experience with essential Docker container lifecycle management, enabling you to clean up your Docker environment and manage resources effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("Docker")) -.-> docker/ContainerOperationsGroup(["Container Operations"]) docker(("Docker")) -.-> docker/ImageOperationsGroup(["Image Operations"]) docker(("Docker")) -.-> docker/VolumeOperationsGroup(["Volume Operations"]) docker(("Docker")) -.-> docker/SystemManagementGroup(["System Management"]) docker/ContainerOperationsGroup -.-> docker/run("Run a Container") docker/ContainerOperationsGroup -.-> docker/ls("List Containers") docker/ContainerOperationsGroup -.-> docker/ps("List Running Containers") docker/ContainerOperationsGroup -.-> docker/rm("Remove Container") docker/ImageOperationsGroup -.-> docker/pull("Pull Image from Repository") docker/VolumeOperationsGroup -.-> docker/volume("Manage Volumes") docker/SystemManagementGroup -.-> docker/prune("Remove Unused Docker Objects") subgraph Lab Skills docker/run -.-> lab-555120{{"How to use docker container rm command to remove containers"}} docker/ls -.-> lab-555120{{"How to use docker container rm command to remove containers"}} docker/ps -.-> lab-555120{{"How to use docker container rm command to remove containers"}} docker/rm -.-> lab-555120{{"How to use docker container rm command to remove containers"}} docker/pull -.-> lab-555120{{"How to use docker container rm command to remove containers"}} docker/volume -.-> lab-555120{{"How to use docker container rm command to remove containers"}} docker/prune -.-> lab-555120{{"How to use docker container rm command to remove containers"}} end

Create and remove a container

In this step, you will learn how to create and remove a Docker container. A container is a runnable instance of an image. You can create, start, stop, move, or delete a container using the Docker API or CLI.

First, let's pull a simple image that we can use to create a container. We will use the hello-world image, which is a very small image that simply prints "Hello from Docker!" and exits.

docker pull hello-world

You should see output indicating that the image is being pulled and downloaded.

Using default tag: latest
latest: Pulling from library/hello-world
...
Status: Downloaded newer image for hello-world:latest
docker.io/library/hello-world:latest

Now that we have the image, we can create and run a container from it. We will use the docker run command.

docker run hello-world

This command will create a new container from the hello-world image, run the command specified in the image (which is to print "Hello from Docker!"), and then the container will exit. You should see the "Hello from Docker!" message in your terminal.

Hello from Docker!
This message shows that your installation appears to be working correctly.
...

After the container has finished running, it will stop. You can see all containers, including stopped ones, using the docker ps -a command.

docker ps -a

You should see output similar to this, showing the hello-world container with a status of "Exited".

CONTAINER ID   IMAGE         COMMAND    CREATED          STATUS                      PORTS     NAMES
<container_id>   hello-world   "/hello"   About a minute ago   Exited (0) About a minute ago             <container_name>

Now, let's remove the stopped container. We can use the docker rm command followed by the container ID or name. You can get the container ID or name from the output of docker ps -a. Replace <container_id> with the actual ID of your container.

docker rm <container_id>

You should see the container ID printed, indicating that the container has been removed.

<container_id>

To verify that the container is removed, you can run docker ps -a again. The hello-world container should no longer be listed.

docker ps -a

The output should not contain the hello-world container you just removed.

Force-remove a running container

In the previous step, we removed a stopped container. However, you cannot remove a running container directly using docker rm. In this step, you will learn how to force-remove a running container.

First, let's create a container that will keep running. We will use the ubuntu image and run a command that keeps the container alive, like sleep infinity. If you don't have the ubuntu image, pull it first.

docker pull ubuntu

Now, run a container from the ubuntu image in detached mode (-d) so it runs in the background.

docker run -d ubuntu sleep infinity

You should see a long string which is the container ID.

<container_id>

Now, let's check that the container is running using docker ps.

docker ps

You should see the ubuntu container listed with a status of "Up".

CONTAINER ID   IMAGE    COMMAND         CREATED          STATUS          PORTS     NAMES
<container_id>   ubuntu   "sleep infinity"   About a minute ago   Up About a minute ago             <container_name>

Now, try to remove this running container using the docker rm command with the container ID. Replace <container_id> with the actual ID of your running container.

docker rm <container_id>

You will likely see an error message indicating that you cannot remove a running container.

Error response from daemon: You cannot remove a running container <container_id>. Stop the container before attempting removal or use -f

As the error message suggests, you need to stop the container first or use the -f (force) flag. Stopping a container can take some time, especially if the process inside the container doesn't respond quickly to the stop signal. Force-removing is a quicker way to remove a running container, although it's generally recommended to stop containers gracefully if possible.

Let's force-remove the running container using the -f flag. Replace <container_id> with the actual ID of your running container.

docker rm -f <container_id>

You should see the container ID printed, indicating that the container has been force-removed.

<container_id>

To verify that the container is removed, run docker ps again. The ubuntu container should no longer be listed.

docker ps

The output should not contain the ubuntu container you just removed.

Remove a container and its anonymous volumes

In this step, you will learn how to remove a container and its associated anonymous volumes. When you create a container, Docker can create volumes to store data. Anonymous volumes are volumes that are not explicitly named when created. They are typically created when a VOLUME instruction is present in the Dockerfile of the image.

Let's run a container that creates an anonymous volume. We will use the ubuntu image again and specify a volume mount point using the -v flag without a name before the colon.

docker run -d -v /data ubuntu sleep infinity

This command creates a container and an anonymous volume mounted at /data inside the container. You should see the container ID printed.

<container_id>

Now, let's inspect the container to see the volume that was created. Replace <container_id> with the actual ID of your running container.

docker inspect <container_id>

The output of docker inspect is a large JSON object. Look for the "Mounts" section. You should see an entry for the volume mounted at /data, and the "Name" field will be a long, randomly generated string, indicating it's an anonymous volume.

...
"Mounts": [
    {
        "Type": "volume",
        "Source": "<volume_name>",
        "Target": "/data",
        "Consistency": "consistent",
        "BindOptions": null,
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],
...

You can also list all volumes using docker volume ls. You should see the anonymous volume listed.

docker volume ls

The output will include the anonymous volume with its randomly generated name.

DRIVER    VOLUME NAME
local     <volume_name>

By default, when you remove a container, its anonymous volumes are not removed. Let's stop the container first. Replace <container_id> with the actual ID of your running container.

docker stop <container_id>

You should see the container ID printed.

<container_id>

Now, remove the stopped container without removing its volumes. Replace <container_id> with the actual ID of your stopped container.

docker rm <container_id>

You should see the container ID printed.

<container_id>

Check the volumes again using docker volume ls. The anonymous volume should still be present.

docker volume ls

The output will still include the anonymous volume.

Now, let's create another container with an anonymous volume and then remove the container and its volume together.

docker run -d -v /data ubuntu sleep infinity

Get the new container ID.

<new_container_id>

Stop the new container. Replace <new_container_id> with the actual ID.

docker stop <new_container_id>

You should see the container ID printed.

<new_container_id>

Now, remove the stopped container and its anonymous volumes using the -v flag with docker rm. Replace <new_container_id> with the actual ID.

docker rm -v <new_container_id>

You should see the container ID printed.

<new_container_id>

Check the volumes again using docker volume ls. The anonymous volume associated with the container you just removed should now be gone. The first anonymous volume you created should still be there.

docker volume ls

The output should only show the first anonymous volume you created.

Remove all stopped containers

In this step, you will learn how to remove all stopped containers at once. As you work with Docker, you might accumulate many stopped containers, which can take up disk space. Docker provides a convenient command to clean up these stopped containers.

First, let's create a few stopped containers. We can use the ubuntu image and run a command that exits immediately.

docker run ubuntu echo "This container will stop immediately"

You should see the output "This container will stop immediately" and the container will exit.

Run the command again to create another stopped container.

docker run ubuntu echo "Another stopped container"

You should see the output "Another stopped container" and this container will also exit.

Now, let's list all containers, including the stopped ones, using docker ps -a.

docker ps -a

You should see the two containers you just created listed with a status of "Exited". You might also see other stopped containers from previous steps if you didn't remove them.

CONTAINER ID   IMAGE    COMMAND                  CREATED          STATUS                      PORTS     NAMES
<container_id_1>   ubuntu   "echo 'This containe…"   About a minute ago   Exited (0) About a minute ago             <container_name_1>
<container_id_2>   ubuntu   "echo 'Another stopp…"   About a minute ago   Exited (0) About a minute ago             <container_name_2>
...

To remove all stopped containers, you can use the docker container prune command. This command will remove all stopped containers.

docker container prune

Docker will ask for confirmation before removing the containers. Type y and press Enter.

WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y

You should see a list of the container IDs that were removed.

Deleted Containers:
<container_id_1>
<container_id_2>
...

Total reclaimed space: ...

To verify that all stopped containers have been removed, run docker ps -a again.

docker ps -a

The output should only show running containers (if any) and no stopped containers.

Summary

In this lab, you learned the fundamental process of managing Docker containers using the docker rm command. You began by creating and running a simple hello-world container, observing its lifecycle from creation to exit. You then practiced removing this stopped container using its ID or name.

Building upon this, you explored more advanced removal scenarios. You learned how to forcefully remove a running container using the -f flag, understanding the implications of this action. Furthermore, you discovered how to remove a container along with its associated anonymous volumes using the -v flag, ensuring a clean removal. Finally, you mastered the efficient technique of removing all stopped containers simultaneously, a useful command for cleaning up your Docker environment.