Docker is an incredible tool for developers and operations, which greatly eases creation and deployment of applications. Yet, one great downside of Docker is the ridiculous amounts of disk space that get eaten by containers, especially on CI systems.

To counter this, regular maintenance of those systems is essential. Docker offers multiple commands to do this. In this article, I explain the ones I use the most for the systems I administer.

General system cleanup

The following commands removes:

  • all stopped containers
  • all networks not used by at least one container
  • all dangling images
  • all dangling build cache

I often run this command in update scripts directly after docker-compose pull, to ensure no longer used images are removed.

Bash
docker system prune --force

The parameter --force skips the interactive confirmation message.

The execution is generally safe when using tools like docker-compose for container management, as volumes are not touched. If you manually manage containers, make sure they're running so they won't be deleted.

Clear builder cache

To speedup builds, Docker keeps a cache which contains all layers of each build step. While this is great for productivity, it can pile up pretty quickly.

Bash
docker builder prune --force --all

The parameter --force skips the interactive confirmation message.

The parameter --all ensures that all layers are removed, not just "dangling" ones.

The execution is generally safe, as the build cache is merely a comfort feature.

Remove unused images

When pulling new versions of container images, old ones will still linger around, and sometimes not removed even if unused. We can force this cleanup:

Bash
docker image prune --force --all

The parameter --force skips the interactive confirmation message.

The parameter --all ensures that all layers are removed, not just "dangling" ones.

The execution is generally safe, as long as all containers are always pulled from remote registries.

The nuclear option

Still need more space? The following command deletes all images on the system.

Use with care, not recommended if any containers are running.

Bash
docker images | awk '{ if(NR>1) print $3 }' | xargs --no-run-if-empty docker rmi -f

The parameter -f to docker rmi makes the rmi subcommand more efficient by also deleting any dependend images or images that have multiple tags.

⚠️ Executing this command requires re-pulling all images needed for your application.