Docker Image cleaning easy automation with cron
Docker makes it easy to ship your applications and services in containers, so you can run them anywhere. Also true is that the more you work with Docker the easier your VM tends to accumulate a huge number of unused images, containers, and data volumes in your filesystem that clutter the output and consume a lot of precious disk space, eventually leading to crashes.
Docker, in newer versions, gives you all the tools you need to clean up your system from the command line. For this, I created a bash script to initialise a cron-job every day at 8am, so it takes responsibility on your system housekeeping, freeing disk space and keeping your system organized by removing unused Docker images, containers, and volumes.
Docker Image bash script to automate the cleaning
In order to keep my own VMs clean, I use the below script to add the “cleaner” to them:
#!/usr/bin/env bash # Setup /opt/docker-cleaner.sh cat <<- 'EOF' > /opt/docker-cleaner.sh #!/usr/bin/env bash echo "========== Docker System Sitting ==========" docker images --quiet --filter=dangling=true | xargs --no-run-if-empty docker rmi -f echo "========== Docker System Cleaned ==========" EOF # Setup cron job for Docker Cleaner chmod +x /opt/docker-cleaner.sh crontab -l > /tmp/newcron echo "0 8 * * * /opt/docker-cleaner.sh" >> /tmp/newcron crontab /tmp/newcron rm /tmp/newcron