Housekeeping containers

In many of the previous examples, when we issued docker ps -a, we saw many stopped containers. These containers could continue to stay in the stopped status for ages if we chose not to intervene. At the outset, it may look like a glitch, but in reality, we can perform operations, such as committing an image from a container and restarting the stopped container. However, not all stopped containers will be reused again, and each of these unused containers will take up disk space in the filesystem of the Docker host. The Docker Engine provides a couple of ways to alleviate this issue. Let's start exploring them.

During a container startup, we can instruct the Docker Engine to clean up the container as soon as it reaches the stopped state. For this purpose, the docker run subcommand supports a --rm option (for example, sudo docker run -i -t --rm ubuntu:16.04 /bin/bash).

The other alternative is to list all the containers using the -a option of the docker ps subcommand and then manually remove them using the docker rm subcommand, as shown here:

$ sudo docker ps -a
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS
NAMES

7473f2568add ubuntu:16.04 "/bin/bash" 5 seconds ago
Exited (0) 3 seconds ago
jolly_wilson

$ sudo docker rm 7473f2568add
7473f2568add
$

Two Docker subcommands, that is, docker rm and docker ps, can be combined together for automatically deleting all the containers that are not currently running, as shown in the following command:

$ sudo docker rm $(sudo docker ps -aq)  

In the preceding command, the command inside $() will produce a list of the full container IDs of every container, running or otherwise, which will become the argument for the docker rm subcommand. Unless forced with the -f option to do otherwise, the docker rm subcommand will only remove the container that is not in the running state. It will generate the following error for the running container and then continue to the next container on the list:

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

Perhaps we could avoid the preceding error by filtering the containers that are in the Exited state using the filter (-f) option of the docker ps subcommand, as shown here:

$ sudo docker rm $(sudo docker ps -aq -f state=exited)

Feeling frustrated at typing such a long and complicated chain of commands? Here is the good news for you. The docker container prune subcommand comes in handy to remove all stopped containers. This functionality is introduced in Docker version 1.13 and here is a sample run of the docker container prune subcommand:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset