Docker Cleanup

Recent versions of the Docker CLI support the prune option in different flavors to keep the system clean.

If your disk capacity is exceeded by Docker’s data folder (e.g. /var/lib/docker) it’s time to cleanup at least the images and this is much more comfortable than usage of filters and pipelines in the past.

But I also want to bring some risks into focus.

Containers

Using docker container prune [--force] you drop all containers that are not Up.

Considering containers which are renamed as fallback or temporarily stopped, there is a medium risk, that you remove more containers than intended.

Images

Using docker image prune [--force] you can cleanup dangling images no longer referenced by a docker resource and no longer tagged. The --force option skips the confirmation as usual.

In standard use cases of Docker with continuous rebuilding of images the risk of loss is minimal. If image prune will remove too many images pulling from a registry or rebuilding should easily restore the original state.

Complex images are an exception to this rule and can impose higher risks.

Dangling vs. Unused

The option --all implements a cleanup of unused images, not referenced by a docker resource, even if they are still tagged.

For example if your containers are only using debian:9, the image for tag debian:8 is not dangling, but unused. So, debian:8 will survive the standard pruning, but not the option --all.

Networks

Using docker network prune [--force] you can cleanup networks on the system no longer referenced by containers.

In standard use cases of Docker (Compose) the risk is also minimal in this context. Compose will rebuild networks in setup.

Volumes

Using docker volume prune you can drop volumes no longer in use.

Even if this sounds reasonable in many cases, there is a high risk you drop persistent data (e.g. database volumes, mail folders, …) in an upgrade process.

I recommend to review the list of volumes (docker volume ls) first before considering the pruning.

System

Using docker system prune will merge all other pruning steps, sums up to the highest risk and is not recommended without review of all the subjects (containers, volumes, …) and confirmation.

Bottom Line

Under normal circumstances with easily deployable Docker setups I would recommend the following for the different prune functions:

  • Regular standard/dangling Image Pruning to keep the storage capacity tight.
  • Network Pruning is also recommended to keep the system clean.
  • Volume Pruning only after review, the more productive your Docker Engine, the less recommended.
  • Image Pruning for unused resources after review.
  • Never run all-in-one System Pruning without review of containers and volumes beforehand. Never run it without confirmation.