Cleaning Up Your Old Docker Containers

Remove old Docker containers

One of the most advantages features of using Docker containers is the ability to quickly spin-up any number of new services instantly. Deploying new versions of our containers can be done just as fast. However, all of this activity eventually means you have a grave yard of old containers sitting around. Learn how to clean your old docker containers with this tutorial.

You may find yourself in an environment that is doing builds every hour or even every few minutes. All of these builds are replacing previous ones, and that means your Docker host’s storage is being overwhelmed by dead containers.

Storage isn’t the only issue. You may be assigned your containers actual names, rather than just having random ones generated for you. If you don’t remove your old containers you won’t be able to use the same names.

The following are solutions that you can use to ensure your old, unneeded contains are being cleaned up regularly.


Periodic Removal of Docker Containers

If you’re not generating a bunch of containers, but you’ve run out of storage, then the following will remove all stopped containers.

docker ps -q -f status=exited | xargs --no-run-if-empty docker rm

Scheduled Removal of Docker Containers

Automating your cleanup task will ensure you keep ahead of your storage issues. We can create a cron job that runs on a regular basis to keep things clean. How often you decide to clean up your old containers depends on how quickly you’re generating new contains and how much storage you have available.

You will need some understanding of how cron works. I won’t go into much detail in this post, but the following examples should help you understand.

The following cron job will run once a week, on a Sunday at 4:00 AM.

0 4 * * 0 docker ps -q -f status=exited | xargs --no-run-if-empty docker rm

The following cron job will run hourly at 15 minutes past the hour.

15 * * * * docker ps -q -f status=exited | xargs --no-run-if-empty docker rm

The following cron job will run once a day at midnight.

* 0 * * * docker ps -q -f status=exited | xargs --no-run-if-empty docker rm