Remove docker unneeded containers and images

Docker does not remove your old containers or images. This is your job, not docker’s.  But, at some point, some cleanup needs to be performed.

It is up to you to decide what to remove.  I show here an example of how I clean my docker containers and images.

How to I do it

List all containers and select, with grep, only containers  that needs to be deleted.

We list containers with docker ps. This command lists  one container per line, with these attributes: CONTAINER ID,   IMAGE,  COMMAND,  CREATED, STATUS, PORTS, CONTAINER NAME :

fc9f4ab5c23c registry:latest "docker-registry" 4 days ago Up 17 hours my_registry 

Deleting not needed containers

These are my rules to delete containers:

  • Do not delete any containers that contain any of these keywords in their name: registry:latest,nexus,keep
  • Only delete Exited containers (not running). In any case, docker will refuse to delete running containers
containers_to_keep=$(docker ps -a | grep 'keep\|registry:latest\|nexus' | awk '{ print $1 }')
containers_to_delete=$(docker ps -a | grep Exited | grep -Fv "$containers_to_keep" | awk '{ print $1 }')
docker rm $containers_to_delete || echo "Could not remove some containers"

Deleting not needed images

For images, I want to keep all latest versions and all images having any of these keywords in their name: keep,nexus.

images_to_keep=$(docker images | grep  'latest\|keep\|nexus' | awk '{ print $3 }')
images_to_delete=$(docker images | grep -Fv "$images_to_keep" | awk '{ print $3 }')
docker rmi $images_to_delete || echo "Could not remove some images"

This is it.

This entry was posted in Cracking the coding interview - a python experience. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s