Docker Image cleaning easy automation with cron

Posted on 3 May 2018 by Alberto Roura.
crondevopsdockerLinux

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

Republished from: Docker Image cleaning easy automation with cron.

πŸš€ Ready to Transform Your Business?

Get expert guidance tailored to your China market ambitions. Our team of cloud and DevOps specialists has helped 100+ companies navigate the complexities of Chinese cloud infrastructure.

From AWS China foundations to ICP compliance, we handle the technical details so you can focus on growing your business.

πŸ“… Schedule Your Free Strategy Session

We'll assess your current setup and show you exactly how to optimize for the China market.

βœ“ No sales pitch β€’ βœ“ Actionable insights β€’ βœ“ Custom recommendations
100+
Companies Served
10+
Years Experience
99%
Client Satisfaction

Not ready for a call? Send us an email instead.