Tidying up Docker Containers and Images using CLI
Over time I have accumulated a lot of Docker containers and images. Just like virtual machines (VMs), I tend to keep the containers in stopped mode till I need them running. This ensures my laptop RAM isn't being used up when I don't need it to.
But recently disk space was low and I realised that I could reclaim some of it.
These are the commands that helped me do just that.
There are some containers I didn't want to delete so I used a bit of
--filters parameter while deleting images.
docker ps -a docker rm angry_ishizaka # At this point realised that doing this manually will take forever
Started deleting multiple in the same command, which led me to doing the following
docker rm competent_gagarin frosty_taussig elastic_turing nifty_jackson docker ps -a -q # This gives me only numeric IDs of the containers docker ps -a -q | tee to-delete-dockers # Redirected the output to a text file for line in `cat to-delete-dockers` ; do docker rm $line; done # Simple BASH for loop
While this cleared the created containers, all the images used to create the containers remain on the disk occupying tonne of disk space.
docker images docker images -a
At this point, realised there are simply too many of them. read the
docker images --help output, didn't find anything interesting.
Found the document on filtering docker images
docker images --filter "dangling=true" # Find images which have no tags
The subshell outputs numeric IDs of dangling docker images and the main command delete the images.
docker rmi $(docker images -f "dangling=true" -q)
This cleared a lot of images which I am pretty sure I wouldn't need. But there were still many more remaining.
I remembered that last week I had tried a Google Kubernetes Micro-services Sample application which had created a bunch of images I didn't need anymore.
The default output of
docker images shows a column
CREATED . Using this as a way to sort, I found the numeric ID of the first docker image created I was able to filter based on time of creation.
docker images --filter "since=07ee12a5eb2a" # Get those images created recently docker rmi $(docker images --filter "since=07ee12a5eb2a" -q) # Add this filter to the previous command
Do note that we can either use
-fthey mean the same thing.
While I have been using
Docker containers for a while now, I wasn't aware of the
--filter parameter. It was very useful in me getting some much needed disk space back.
So all in all a great way to tidy up docker container and images using the command line.