Each time I build an image with docker, it gets tagged with the project identifier. You know, Something like ‘$ docker build -t cfreeman/reprage .’ The problem is that old images don’t get cleaned up, they just get left behind. Dangling until I clean them up, usually when I hit an inevitable ‘no space left on device’ error when building something.

 cfreeman/reprage   latest              c71e362c3635        4 minutes ago       755.1 MB
 <none>             <none>              58393936e5f1        7 weeks ago         754.3 MB
 <none>             <none>              4eaee92d2db0        7 weeks ago         754.2 MB
 <none>             <none>              337bf3d01226        8 weeks ago         754.2 MB
 <none>             <none>              5335ebaadca3        9 weeks ago         753.5 MB
 <none>             <none>              ef5f6cb0a7a0        10 weeks ago        753.4 MB

Ugh, such mess and much wasted space. I use the following bash script to prune out the old unused docker images:

 #docker-clean.sh: Removes all images that have don't have a tag.

 docker images | grep '<none>' | while read -a line ; do
     docker rmi -f ${line[2]}

The script uses grep to filter output from docker to return only the images without a tag. Bash builtins (‘while’ and ‘read’) are used to read one line at a time from the filtered output. These lines get broken into words and sequentially assigned to an array. The docker image ID lives at index ‘2’ of this array, the ID is used to remove the image from docker.

comments powered by Disqus