paulund

Clean Up Docker

Clean Up Docker

Downloaded images and containers accumulate over time and can consume a significant amount of disc space — particularly images from older projects you no longer develop on. Docker makes it straightforward to remove these unused resources. If you ever need an image again, Docker will pull it from the registry automatically.

Check Current Usage

Run the following command to see how much space images, containers, volumes, and build cache are currently using:

docker system df

Example output:

TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              23                  9                   2.62GB              2.007GB (76%)
Containers          24                  1                   28.71MB             28.71MB (100%)
Local Volumes       71                  6                   1.217GB             1.216GB (99%)
Build Cache         0                   0                   0B                  0B

In this example, over 3 GB of space is available to reclaim.

System Prune

docker system prune is a catch-all command that removes stopped containers, unused networks, dangling images, and dangling build cache in one step:

docker system prune

This is a good starting point, but it does not remove unused volumes or images that are tagged but not attached to a running container. Use the more targeted commands below for a thorough clean-up.

Image Prune

To remove all images that have no container associated with them — including tagged images — use the -a flag:

docker image prune -a

After this runs, only images with at least one associated container remain locally. Confirm the result with docker system df.

Container Prune

Remove all stopped containers:

docker container prune

You can limit the scope using the --filter flag. The following example removes only containers that stopped more than 24 hours ago, leaving recently stopped containers untouched:

docker container prune --filter "until=24h"

Volume Prune

Remove all volumes that are not in use by at least one container:

docker volume prune

Be cautious here. Volumes may hold persistent data. Verify that you do not need the data before pruning.

Automating the Clean-Up

You can reclaim space on a schedule by adding a cron job. The following example runs an aggressive prune every Sunday at 02:00, writing output to a log file:

# Add to crontab with: crontab -e
0 2 * * 0 /usr/bin/docker system prune -af --volumes >> /var/log/docker-prune.log 2>&1

The flags used here:

  • -a — remove all unused images, not just dangling ones.
  • -f — do not prompt for confirmation.
  • --volumes — also remove unused volumes.

Run docker system df before and after any prune to measure the reclaimed space.