Cleaning up Docker Compose images

Posted by Rivo Laks on 12 April 2018

I often hop between different projects, many of them using Docker Compose. Its unfortunate side-effect is that over time I end up with lots of Docker images of projects I’m no longer working on, or currently not working on. Eventually all those images can really eat into your disk usage and some spring cleaning is in order.

For those unfamiliar with Docker Compose, it provides an easy way of defining a project consisting of multiple Docker containers working together. For example, suppose your project has a container running Django app, another container dealing with web assets using Node, plus a PostgreSQL database. You can then define a Docker Compose project listing all those different containers (services) and get them all up & running with a single command. Docker Compose then creates multiple images and containers, named e.g. myproject_django, myproject_node, etc. In Thorgate we use Docker Compose for pretty much all (web) projects and have published a project template making use of it.

One could clean up the situation by running docker image list | sort, manually going through the list and finding the unused images, and finally removing them by running docker image remove image_one image_two .... But when you have a long list of Docker images and Docker Compose projects, that can be quite a bit of effort…

So I made a small tool which helps specifically with cleaning up Docker Compose images. The idea is to make use of Docker Compose’s image naming scheme — images of Compose projects are named projectname_servicename, using underscore as separator. We could thus find all images matching that naming scheme, figure out the project name, and then present them to the user grouped by the project.

The project is published to PyPI as docker-compose-cleanup. To try it out, first install the package into a Python 3 environment

pip install docker-compose-cleanup

Next, run the script itself (or its doco-cleanup alias):

docker-compose-cleanup

The results are presented as docker image rm ... commands, with the intention that you can easily copy & paste commands that remove images of projects I’m no longer interested in. Output should look something like:

Images without tags:
docker image rm sha256:c8f20d0f9a sha256:462683af4d
Project images:
myproject
docker image rm myproject_django:latest myproject_node:latest myproject_celery:latest
pycharm
docker image rm pycharm_helpers:PY-181.4203.547
thtools
docker image rm thtools_app:latest

If I wanted to get rid of myproject images, I can just triple click on that line to select the entire line, and then copy-paste it into the same terminal window.

Hopefully you’ll find it useful. Feel free to report any issues and feature requests on Github. If you’re interested in how the sausage is made, the main code is in this file.

Title photo by Scott Webb on Unsplash