Deleting unused docker images "automatically"

published at

So I have a cheap server with no single source code, all apps are managed under docker images. I rarely do ssh to my server, since I'm using GitLab CI/CD to deploy my app.

Then I just got email from GitLab telling me that one of my pipeline was fail. I do CI (build & test) in every PR/new branch and using full pipeline only when merging to primary branch, so I curious by that email since the build & test process was pass. Yeah, this is common problem. My data directory was only ~963M, but my df -h was used ~13G. I know this is mostly from either docker images and docker container.


Let me tell you how my docker images looks like. And this is my docker process looks like I have 10 apps running with 3 different kind databases. All my apps that deployed via CI/CD I only care with staging or latest tag, otherwise I'm assumed it was 'old version'.

And I need to remove it to keep my fs lean.

The Old way

All my unused images are basically has <none> on their version tag. I can do

docker images | grep "<none>"

For it and remove the images.

But now I rarely *ssh-ing *to my server, mostly because my lazyness. I need a clever way to do that without making my hand dirty.

Sooo it was a combination between Cron + some command. The conclusion from this post.

The new way

I need to delete all unused images, checked every 1 hour. Because this was a lean command that doesn't need heavy cpu and if there is no unused images, docker will simply do nothing.

First of all, we need to check it with command previously

docker images | grep "<none>"

Docker will give you some output, but all you need is only its ID. I know some awk so let's take only the third column. After that we can use this command to delete the (unused) images.

docker rmi $(docker images | grep "<none>" | awk '{print $3}')

That's it.

cron cron cron

Above command was solves my problem, but I need to make it more lazy to save me more time. Thanks GNU/Linux, we have cron! So I set some cron script every hour to execute the script. It works!

Although I use zsh and bash, I prefer to execute the script via sh after doing some "hello world" benchmark here.


All you need is only save this shell script:

docker rmi $(docker images | grep "<none>" | awk '{print $3}')

in somewhere, tell cron to execute it, than, enjoy your life. This solution is not best but at least works for me.