5 ways to find and remove unused docker containers


Docker

Docker is a powerful platform that allows users to package and run applications within loosely isolated environments called containers. Compared with traditional virtual machines, containers can be lighter weight, and thus allow more efficient resource usage of the underlying system. Nevertheless, it’s common for users to accumulate numerous unused or temporary containers over time – which consume disk space unnecessarily and may degrade the performance of your system. So it is necessary to manage these redundant Docker containers rightly to keep a clean and efficient computing environment.

To properly remove unused Docker containers, you must first identify them and then delete in order to release space safely. There are several ways you can do this:

  • Manual removal of specific containers: If you know which ones are not needed anymore, you can delete them directly using docker rm command along with their names or IDs;
  • Automatically removing stopped containers: Docker allows cleaning up all stopped containers at once what often happens when they are not in use any longer;
  • Remove by criteria using filters: You may set filters based on different conditions like exited status etc., so only those matching will be targeted;
  • Automatic cleanup on container exit setting: For tasks where data persistance is not required during container runtime, --rm flag can be utilized which tells Docker to automatically remove the container after it stops;
  • Bulk removal with Docker Compose: In case if you work with Compose multiple services can be removed together – this is handy when cleaning up after testing or development.

 

List Running Containers

Before you plan to remove unused docker containers, you must know the list of running containers so that you can filter them and then plan to remove accordingly.

 

1. Checking All Running Containers

You can list all the running containers and navigate through the list to identify unused containers.

docker ps

This command outputs a list of all currently running containers, showing details like container ID, image being used, when they were created, their status, and ports that might be open and mapped.

Now the output of above command can be overwhelming so we can format the output with the important fields only such as container ID, name, status of the container and most importantly the date when the container was created. Based on this information you can plan to determine any unused containers.

docker ps -a --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.CreatedAt}}"
5 ways to find and remove unused docker containers

For more information you can further use docker inspect with the respective container ID:

docker inspect --format='{{.State.StartedAt}} {{.State.FinishedAt}}' [container_id]

This command will help you get the start and finish time of the container:

5 ways to find and remove unused docker containers

 

2. Checking All Unused Containers

The term 'unused' can mean different things for different people. While there is no such in built argument which we can pass to docker and get the list of 'unused' containers but we can add some filters and print all containers which are in exited state which most likely means that no one is using them:

docker ps -a -f "status=exited"
5 ways to find and remove unused docker containers

 

Methods to cleanup unused docker containers

Now that we have the list of running containers and you should also have a fair idea of all the unused containers so let's jump to the commands and methods which can be used to delete and cleanup these unused docker containers.

 

1. Remove a Specific Container

If you don't have a long list then you can just remove a single or specific container using the container ID or name. You can either pass a single container ID or multiple ID which needs to be deleted.

docker rm [container_id_or_name1] [container_id_or_name2] [container_id_or_name3] ...

For instance, if you want to remove a container with the ID 12345abcde, you would use:

docker rm 12345abcde

This command will remove the provided container. But please NOTE that the container must be in STOPPED state before it can be removed. So if the container is in running state, then you can stop it first using docker stop [container_id_or_name] or alternatively add the -f (force) option to remove it while running, though this is not recommended for production environments as it might lead to data loss.

docker rm -f container1 container2 container3

 

2. Remove All Stopped Containers

You can remove all stopped containers using the prune argument with docker command:

docker container prune
5 ways to find and remove unused docker containers

Be cautious when running this command as this will delete all containers which are in stopped state. This command does not care if a container was used recently or not and it will just check the current status and delete the container if in stopped state.

You can further use until filter to further control the prune operation based on timeline. For example to prune all containers in stopped state for more than 24 hours we can use:

docker container prune --filter "until=24h"

There is also a way in docker to keep a container always in running state to avoid accidental deletion.

 

3. Remove Containers Using Filters

We already discussed about status=exited filter which will list all containers which are in exited state. So we can combine docker rm with docker ps to list all exited containers and directly delete them using single command:

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

 

4. Automatic Container Cleanup on Exit

Now this method is not directly linked to cleanup of unused docker containers but instead it will fix the source of the problem. The whole reason why we have these unused containers is because we access them using docker run command and then forget to delete them over the period of time. So to avoid that we can make a habit to start a container with --rm argument so that the docker will automatically clean up the container and remove the file system when the container exits.

docker run --rm [image]

You can read more about --rm flag at Running containers.

 

5. Automatic container cleanup

You can go for a script based solution if you have a requirement to perform automated cleanup of containers based on some timestamp or container status which we have discussed in this tutorial.

Here's a basic bash script that lists all stopped containers and the time they last exited. It checks if they have been inactive for more than a specified number of days:

#!/bin/bash
threshold_days=7
current_time=$(date +%s)

# List all exited containers and get their IDs
docker ps -a --filter "status=exited" --format '{{.ID}}' | while read id
do
    # Use docker inspect to get the FinishedAt time for each container
    finished=$(docker inspect --format '{{.State.FinishedAt}}' $id)

    # Simplify the timestamp to a format that 'date' can handle
    simplified_finished=$(echo $finished | sed 's/\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\} [0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}\)\..*/\1/')

    # Convert FinishedAt time to Unix timestamp
    finished_at=$(date -d "$simplified_finished" +%s)

    # Calculate the difference in days between current time and finished time
    let "diff = (current_time - finished_at) / 86400"

    # Check if this difference is greater than the threshold
    if [ $diff -gt $threshold_days ]; then
        name=$(docker inspect --format '{{.Name}}' $id)
        # Remove leading '/' from container name
        name=${name#/}
        echo "Container $name ($id) has been inactive for more than $threshold_days days."
    fi
done

Output from this script will list all the containers that have been inactive for more than the provided threshold days:

5 ways to find and remove unused docker containers

Now you can alter the script to perform the cleanup at the end of the execution and run the script as part of some cron job for regular monitoring and execution.

 

Summary

In order to manage Docker efficiently, one must regularly clear unused containers that consume resources. Non-running containers are listed by running docker ps -a --filter "status=exited" which shows all those which have stopped but not removed. To delete specific containers we can use docker rm followed by their IDs; for broader clean up we may want to try out docker container prune that removes all stopped containers hence freeing up space occupied by such redundant instances. It is possible to automatically remove them once they stop if persistent data is not required using docker run --rm. Moreover, through scripting one can automate detection and removal of containers inactive for some time thus improving efficiency within the system itself. These commands should be used on a regular basis so as to keep Docker well organized and utilize system storage as well processing power optimally

 

Views: 83
Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment