Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 53 of 8021. Container FundamentalsFree lesson

Removing Stale and Stopped Containers

Implement cleanup strategies to reclaim system resources by effectively purging containers that are no longer in use.

In this lesson, you will learn how to maintain a healthy system environment by purging containers that are no longer active, effectively reclaiming valuable disk space and memory.

Why Clean Up?

Every time you run a container, Docker allocates resources to track its filesystem layers and runtime state. Even after you stop a container, it remains on your system as a "stopped" container. If you frequently test applications or perform CI/CD builds, these inactive containers pile up, consuming disk space and making it difficult to find the containers you actually care about.

Identifying and Removing Stopped Containers

When a container is in a Stopped state, it is essentially "stale." It isn't doing any work, but it is taking up space. To see all your containers—including the ones that are not currently running—you can use:

docker ps -a

If you notice a list full of containers with an Exited status, they are perfect candidates for removal. You can remove a specific container by its name or ID:

docker rm <container_id_or_name>

The "Prune" Shortcut

Manually removing every single container one by one is inefficient. Docker provides a powerful command to instantly remove all stopped containers at once. This is the gold standard for maintaining a clean host:

docker container prune

This command acts like a "garbage collector." It looks at your system, identifies every container that is not currently running, and wipes them away. By incorporating this into your development workflow or CI/CD pipelines, you ensure that your local machine or build server doesn't hit storage limits due to "container bloat."

Remember, always double-check that you haven't left any data inside a container that you needed to save (though, as you learned in earlier lessons, you should be using Volumes for permanent data storage anyway!).

Key Takeaway: Regularly running docker container prune is a best practice that keeps your environment performant by removing stale containers and freeing up system resources.