Docker Purge

My relation with docker is … well mixed.

Constantly I am oscillating between “I love docker” and “I hate docker”. This happens in a matter of seconds, many times per day.

The containers I run are mostly locally, I do not use it on the server.

My primary use case is during development of software: It’s nice to run your Unit-Tests against the real deal instead of mocking everything away. That would be for example some MySQL database in Testcontainers instead of using some In-Memory database or something. They behave little bit different than the real deal, drawing in subtle bugs that only occur later in production. Horrible.

Doing cross compiling of software is my other use case: Starting from a clean system, drawing in only required dependencies and then running the build during container creation. This keeps your normal system clean, and comes with the benefit that every build step is automatically documented: every step is part of the Dockerfile. When it finally works you have already written down every detail how to setup the environment and every step how to build it. Nice!

So enough of the introduction - why I am writing this post?

It turns out that sometimes you leave some broken state behind. Old containers are still running, eating up resources of your machine, unused volumes still lurk around, the network setup is all messed up…

Sad.

But there is a solution. I use these helper snippets in my shell rc to address the cleanup parts.

This one is obvious - If I want to try something out, not messing up the shell history this comes in handy:

alias focker="docker"

To actually remove all running containers, images, volumes and whatnot there are these functions:

function dockerpurge-containers() {
  echo ":: docker containers"
  docker container ls --all --quiet | xargs docker container rm --force
}
function dockerpurge-images() {
  echo ":: docker images"
  docker image ls --all --quiet | xargs docker image rm --force
}
function dockerpurge-volumes() {
  echo ":: docker volumes"
  docker volume prune --all --force
}
function dockerpurge-network() {
  echo ":: docker network"
  docker network prune --force
}
function dockerpurge-cache() {
  echo ":: docker builder"
  docker builder prune --all --force
}
function dockerpurge-system() {
  echo ":: docker system"
  docker system prune --all --force --volumes
}
function dockerpurge() {
  echo ":: :: :: ::"
  dockerpurge-containers
  dockerpurge-images
  dockerpurge-volumes
  dockerpurge-network
  dockerpurge-cache
  dockerpurge-system
}

So to remove all running containers I run dockerpurge-containers, to actually reset everything dockerpurge does it’s job. Then I can start over from a clean state.

This is nice, and helps me to say “I hate docker” less often…

So long!