Saturday, 27 August 2022

How to Remove Exited Docker Containers

Docker containers can sometimes exit unexpectedly or remain in an "exited" state, taking up valuable system resources. In this guide, we'll explore different methods to identify and remove these exited containers.
Identifying Exited Containers
First, let's see how to identify exited containers. You can use the following command to list all containers, including exited ones:
docker ps -a
To specifically filter for exited containers, use:
docker ps -a | grep "Exited"
CONTAINER ID        IMAGE                      COMMAND                  CREATED             STATUS                     PORTS                                        NAMES
9b65cedfc4b3        d0eadfcacdc2               "/bin/sh -c 'apt-get…"   10 months ago       Exited (1) 10 months ago                                                stupefied_kirch
c3edc0a8c3c6        7aa9bc2b797e               "/bin/bash"              10 months ago       Exited (0) 10 months ago                                                wonderful_mirzakhani
7f20f353fa7b        7aa9bc2b797e               "/bin/sh -c 'apt-get…"   10 months ago       Exited (1) 10 months ago                                                zen_payne


Methods to Remove Exited Containers

Using docker container prune:
simplest way to remove all stopped containers is using the docker container prune command:
docker container prune -f
Deleted Containers:
9b65cedfc4b37b5754e0a16709b387a2c5c39999412908be0a4f6c23da72c29d
c3edc0a8c3c6c2d46712637c58be22e801f46a140608c89fb0ff38d968837a06
7f20f353fa7b7a7c3ae3b6780bfc96021792a9761d99aff88f4503f30df53c95
Total reclaimed space: 310.1MB


The -f flag forces the removal without asking for confirmation. This command will:
1.Remove all stopped containers
Show you which containers were deleted
Display the total space reclaimed

2. Removing Specific Containers
If you want to remove a specific exited container, you can use its container ID:
docker rm <container_id>

3. Removing All Exited Containers
To remove all containers that are not running, use:
docker rm $(docker ps -a -q -f status=exited)

Verifying the Cleanup
After removing the containers, you can verify that all exited containers have been removed:
docker ps -a | grep "Exited"

No comments:

Post a Comment