Skip to content

Instantly share code, notes, and snippets.

@isopropylcyanide
Created June 3, 2020 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isopropylcyanide/61375334eee124806500b19e1a9aafd2 to your computer and use it in GitHub Desktop.
Save isopropylcyanide/61375334eee124806500b19e1a9aafd2 to your computer and use it in GitHub Desktop.
Docker Disk Prune Cron Script
#!/bin/bash
# =====================================================================================================================
# This script helps prune docker disk for dangling images, unused containers or images. Use this in a cron tab for
# automatic disk maintenance. While this alone cannot clear most of the fragmented disk which are cleared by restaring
# the daemon, it only delays the point in time where we have to eventually restart the daemon and clear i-nodes
# Usage $ chmod +x docker-disk-prune.sh
# Recommended cron expression (every 3 hours)
# * */3 * * * sh /docker-prune.sh
#
# Created by : Aman Garg
# This script automatically rotates after the threshold is reached. Nothing is required
# =====================================================================================================================
log=prune.log
log_max_size=5000000 #50 MB
# Do nothing if docker is not installed
if ! hash docker 2>/dev/null; then
echo "Docker is not installed"
exit 1
fi
# Create file if it doesn't exist
touch -a $log
# if file size has exceeded the threshold (50 MB), we rotate
current_log_size=$(du ${log} | awk '{print $1}')
if (( current_log_size >= log_max_size ))
then
$(echo -n "" > $log)
echo 'Rotated file ' >> $log
else
echo "Current size $current_log_size < $log_max_size (threshold)" >> $log
fi
echo "" >> $log
echo "*********************************" >> $log
date +'=== %Y.%m.%d %H:%M ===' >> $log
#Report current used size
echo "" >> $log
echo "Before " >> $log
docker system df | awk '{print $1 , $4}' >> $log
#Pruning all unused images without prompt
docker system prune -af >> $log
#Report new used size
echo "" >> $log
echo "After " >> $log
docker system df | awk '{print $1 , $4}' >> $log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment