Tidy up unused Docker Containers and Images

Every now and then I catch me unprepared when the pile of Docker images threatens the normal operation of our Jenkins server. So I decided to write about the command lines we use as a broom to keep our server clean.

Remove all stopped containers

$ docker rm --volumes $(docker ps --all --quiet --filter status=exited)

The nested command will list the IDs only (--quiet) of all (--all) exited containers (--filtered status=exited) This outer command removes (rm) the containers listed by the nested command including the volumes associated with the container (--volumes).

For the sake of completeness here the short form:

$ docker rm -v $(docker ps -a -q -f status=exited)

Remove all dangling images

Here we started with the grep-and-awk variant:

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

but modified the command over time and went with the more readable form:

$ docker rmi $(docker images --all --quiet --filter dangling=true)

or the short variant:

$ docker rmi $(docker images -a -q -f dangling=true)

Let's keep the build environment a clean and tidy place.

Remove all dangling volumes

$ docker volume rm $(docker volume ls -q -f dangling=true)

Kudos go to Docker remove all dangling volumes from Coderwall.

Automation with Cron

As a devop user with access to the docker daemon you can automate this process:

$ crontab -e

and add something like:

# Cleanup docker artifacts regularly. Remember: stopped containers are removed every night!
10 2    * * *   docker rm --volumes $(docker ps --all --quiet --filter status=exited) >> /var/log/devop/docker-container-cleanup.log
20 2    * * *   docker rmi $(docker images --all --quiet --filter dangling=true) >> /var/log/devop/docker-images-cleanup.log

Note: You will need to create a log directory for your devop: /var/log/devop.

Show Comments