Removing A Container
We can remove a container permanently, but before that, we have to stop the container or use the force option. In this recipe, we’ll create and remove a container.
Getting ready
Ensure that the Docker daemon is running on the host and can be connected through the Docker client. You will also need some containers in a stopped or running state to delete them.
How to do it…
Use the following command:
$ docker container rm [OPTIONS] CONTAINER [CONTAINER]
Or run the following legacy command:
$ docker rm [OPTIONS] CONTAINER [CONTAINER]
Let’s first create a container, and then delete it using the following commands:
$ ID=$(docker container create ubuntu /bin/bash)
$ docker container stop $ID
$ docker container rm $ID

As we can see from the preceding screenshot, the container did not show up, which just entered the docker container ls command after being stopped. We had to provide the -a option in order to list it.
There’s more…
To remove a running container, it must be stopped first using the docker container stop command and then removed using the docker container rm command.
To forcefully remove a container without intermediate stop, use the -f option of the docker container rm command.
To remove all the containers, we first need to stop all running containers and then remove them. Be careful before running these commands as they will remove both running and stopped containers:
$ docker container stop $(docker container ls -q)
$ docker container rm $(docker container ls -aq)
There are options to remove a specified link and volumes associated with the container, which we will explore later.
How it works…
The Docker daemon will remove the read/write layer, which was created while starting the container.
See also
Look at the help option of docker container rm :
$ docker container rm --help
The documentation on the Docker website can be found here: https://docs.docker.com/engine/reference/commandline/container_rm/.