Docker Remove All Stopped Containers

In this quick guide, we will see how to remove all stopped Docker containers to maintain a clean and efficient workspace.

The Need for Cleanup 

Before diving into the process, let's address the "why" behind cleaning up stopped containers: 

Free Disk Space: Over time, many stopped containers can lead to substantial disk space consumption.

Clarity: Cleaning up provides a clearer view of active containers, reducing confusion and potential mistakes. 

Performance: It's easier to manage and back up a Docker system with fewer containers, leading to faster response times.

Example

1. Identifying Stopped Containers 

The first step is to check and list all the containers, including the stopped ones:

docker ps -a

The list will include active and stopped containers, with their status clearly marked as 'Up' or 'Exited', respectively.

2. Removing Stopped Containers

The Command To remove all stopped containers in one go, use the following command:

docker container prune

Upon execution, Docker will prompt you for confirmation. Once you confirm, it will remove all containers with an 'Exited' status.

The docker container prune command is a specialized command designed specifically to clean up unused containers. Here's what happens: 

  • Docker inspects the status of all containers. 
  • It identifies containers that are not running (with 'Exited' status). 
  • Post-confirmation, it deletes these containers, freeing up disk space.

3. Verifying the Cleanup 

After running the cleanup command, recheck your list of containers:

docker ps -a

The list should now display only the active containers (if any), indicating that all stopped containers have been removed.

Another Way to Remove All Stopped Containers

To delete all stopped containers, you can combine the power of docker ps with docker rm:

docker rm $(docker ps -a -q -f status=exited)

Here's what's happening in this command: 

docker ps -a -q: Lists all containers (including stopped ones) and outputs only their container IDs. 

-f status=exited: Filters the list to only show stopped containers. 

docker rm: Removes each container in the list.

After executing the command, it's a good practice to check that all stopped containers have been removed:

docker ps -a

Conclusion

Both the docker container prune method and the docker rm $(docker ps -a -q -f status=exited) method achieve the same result. The docker container prune is more concise and user-friendly, the docker rm $(docker ps -a -q -f status=exited) method gives you a granular level of control and can be adapted for other complex filtering tasks.

Related Container Management Guides

Comments