Clean up Docker images that are taking up space
The Problem
You deploy, you rebuild, you test things. And one day, you look at your server and you have only 2 GB of free space left. Congratulations, Docker has eaten it all up. Your Docker hard drive hates you. And itโs your fault.
What exactly is the problem? Docker accumulates images over time. Every time you run docker build, if anything changes, it creates new layers and keeps the old ones. These old layers, which have no tags, no names, and no purpose, are called dangling images. They serve no purpose. They take up space. And Docker doesnโt delete them on its own.
See Where You Stand
Before deleting anything, thereโs just one thing to do:
docker system df
This shows you in a few lines how much space is being used - and, more importantly, how much is available. Thatโs your starting point.
Want to see the images in detail?
docker images --format "table {{.Repository}} \t {{.Tag}} \t {{.ID}} \t {{.Size}}"
Delete Dangling Images
Dangling images are intermediate layers that are left behind. They have neither a tag nor a name. To delete them:
docker image prune
Docker asks for your confirmation, shows you what it's going to delete, and you confirm. Clean, fast, and risk-free.
Go a Step Further
If you have entire images that are no longer used by any container (even stopped ones), you can delete them as well:
docker image prune -a
The -a option changes everything: now it no longer targets just dangling images, but all unreferenced images. Thatโs what you want in most cases on a production or staging server.
You can filter by age if you want to keep recent images:
docker image prune -a --filter "until=720h"
It only deletes items that are more than 30 days old. This is handy if you have regular deployments.
Reset Everything
If you want to reset everything - images, stopped containers, orphaned volumes, unused networks:
docker system prune -a --volumes
I donโt recommend doing this on a production server without first checking whatโs running. But on a dev machine or a VPS that you rebuild regularly, itโs perfect.
Automating All of This
Instead of doing this manually, you can set up a weekly cron job:
# crontab -e
0 3 * * 0 docker image prune -a -f >> /var/log/docker-prune.log 2>&1
Every Sunday at 3 AM, it cleans up without asking for confirmation (-f), and logs the result.
Conclusion
| Command | What it does |
|---|---|
docker system df |
View used space |
docker image prune |
Remove dangling images |
docker image prune -a |
Remove everything that is no longer in use |
docker image prune -a --filter "until=720h" |
Same as above, but only for old images |
docker system prune -a --volumes |
Reset everything to zero |
Start with docker system df. In 90% of cases, running docker image prune -a is enough to free up several gigabytes without breaking anything.
Top comments (0)
Comments
No comments yet. Start the discussion.