The other day, I was alerted to a storage space alarm on a Linux system that hosts a handful of Docker containers. Having had a few go arounds with Docker and logs filling up disks, I suspected that but logs weren’t to blame here. In this case, what was taking up considerable space was a decent collection of container images that accumulated over time. This post will review some basic troubleshooting and how to handle some basic Docker image maintenence.
First, let’s talk about how you get to this point. When you build or pull a new version of an image to update a container, in the end, the old container image isn’t automatically deleted. Instead, it remains stored locally on disk. Over months of automated deployment or iterative testing, dozens or hundreds of gigabytes of stale images accumulate under /var/lib/docker.
As always, take a snapshot or some other backup that you can rely on.
Step 1: Check Storage Allocation Across Docker
Before running destructive commands, inspect how Docker is distributing disk usage across images, containers, local volumes, and build cache. The output will show you the amount of Images and the space the consume along with how much space is reclaimable. This also shows the same info for actual Containers, Local Volumes, and the Build Cache
docker system df
Step 2: Inspect Active and Stopped Containers
Before purging images, or anything for that matter, verify which containers exist on the host so you don’t accidentally attempt to wipe an image tied to a stopped but vital service.
docker ps -a
Step 3: List All Local Docker Images
Inspect all locally available images, including tags, Image IDs, and sizes. Take note of the Image ID, which you may use in the next step providing you want to delete specific images.
docker image ls
Step 3: Cleaning Up
Option 1 – If you want to manually delete a specific, obsolete image by its ID
docker image rm <image_ID>
Note on Container Dependencies – If Docker prevents deletion with an error stating the image is referenced in a stopped container, you must either remove the stopped container first (docker rm ) or force removal (docker image rm -f )
Option 2 – Rather than deleting individual images by ID, to sweep away all untagged and dangling images safely, in that active and tagged images remain untouched
docker image prune
Option 3 (Full Cleanup) – If you want to fully delete all unused images AND stopped containers AND unused networks AND build caches in one sweep
docker system prune -a
When you’re all set, revisit Step 1 to see where you landed. Of course, you can also run below to see how the overall storage capacity has changed
df -ah