Pruning stale docker items
code

Pruning stale docker items

Getting rid of that Docker bloat

The Lad 1 min read
Read More
Older Post Newer Post

Unbeknownst to me, I was inadvertently adding files to the docker overlay2 directory when I was debugging/troubleshooting a container using the docker build command. That and over a year of updates and other life things led to a usage of ~ 21GB of stale builder cache lying around. ๐Ÿ˜ฑ

The Solution

A quick one-time cleanup:

docker builder prune

This freed up 21GB immediately!

Automation

To avoid this cruft in the future, I've added a weekly cleanup to root's cron daemon:

# Runs weekly on Sunday at 3 AM
0 3 * * 0 date >> /var/log/docker-prune.log && /usr/bin/docker builder prune -a -f --filter "until=168h" >> /var/log/docker-prune.log 2>&1

This keeps the last week's cache warm for faster rebuilds while removing older unused layers.

A few notes about the flags:

  • -a removes all unused cache, not just dangling layers
  • --filter "until=168h" preserves the last 7 days
  • -f runs without confirmation (necessary for automation)

Optional Enhancements

Log Rotation

Prevent the log file from growing indefinitely:

# Create /etc/logrotate.d/docker-prune
/var/log/docker-prune.log {
    weekly
    rotate 4
    compress
    missingok
    notifexist
}

More Comprehensive Cleanup

If you also accumulate unused images:

# Add image pruning to the cron job
0 3 * * 0 date >> /var/log/docker-prune.log && \
  /usr/bin/docker builder prune -a -f --filter "until=168h" >> /var/log/docker-prune.log 2>&1 && \
  /usr/bin/docker image prune -a -f --filter "until=168h" >> /var/log/docker-prune.log 2>&1

Or for a more aggressive system-wide cleanup (includes containers, volumes, networks):

docker system prune -a -f --filter "until=168h"

โš ๏ธ Be careful with --volumes if you have persistent data stored there!


This automation should keep Docker's appetite for disk space in check while maintaining good rebuild performance. ๐Ÿงน