Docker: Clean up unused stuff on your development machine

Time to shovel out the shit.

Docker keeps all objects (images, containers, volumes, etc.), with no automatic cleanup. It thus consumes disk space without bound, which can eventually fill up your development machine.

To clean up all objects older than 24 hours that are not currently in use, run these two commands:

$ docker system prune --all --force --filter until=24h && docker volume prune --force

Whilst system prune can clear volumes with --volumes, that option isn’t compatible with --filter, so two commands are required. Drop --filter until=24h option to clean up newer objects too. For more info on these commands, see the Docker manual page Prune unused Docker objects.

The --force option skips the prompt, which has a warning but no information on exactly what will be removed. Here’s what it looks like:

$ docker system prune --all
WARNING! This will remove:
  - all stopped containers
  - all networks not used by at least one container
  - all images without at least one container associated to them
  - all build cache

Are you sure you want to continue? [y/N]

Here’s the edited output from an example run:

$ docker system prune --all --force && docker volume prune --force
Deleted Containers:
8bf725f779c45582d01dbad17c05c728919b29fbe49d464cec8a553d02a95585
...

Deleted Networks:
example
...

Deleted Images:
untagged: ghcr.io/hadolint/hadolint:latest
...
deleted: sha256:2d306e4c9d04b921299cd213188190c86fdfef73d2cab02aa61a2e4e787c2baf
...

Deleted build cache objects:
zkvg3lzxi1fxy4r0e1hwaop6o
...

Total reclaimed space: 36.71GB

Deleted Volumes:
37c01681e8d832e9c36502f22a274a83f9677cc3c437734f92777025eedcbb6c
...

Total reclaimed space: 1.012GB

I reclaimed nearly 38GB of disk space!

I have an every-two-weeks calendar event reminding me to run the cleanup one-liner. I prefer this over automatic execution since sometimes I may not want to clean up everything, such as when working with a poor internet connection.

Check reclaimable space

Preview the amount of space reclaimable with the system df subcommand:

$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          5         5         4.296GB   180MB (4%)
Containers      5         5         1.778kB   0B (0%)
Local Volumes   3         3         438.5MB   0B (0%)
Build Cache     51        0         1.24GB    1.24GB

Alternatively, the Disk Usage extension for Docker Desktop shows this information in a ring chart, with a “Reclaim space” button to run docker system prune.

Fin

May your disks stay light and agile,

—Adam


😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Tags: