This problem is common when you are using docker to deploy application on serve. Every time a new docker image is pushed on server it occupies some memory and over the time it occupies a significant amount of disk space on server. to resolve this issue you can either run the following command manually
sudo docker system prune -a -f
or you can use the following script and set a cronjob to run it after a desired time of your choice:
#!/bin/bash TIMESTAMP=$(date +"%d-%m-%Y_%H-%M-%S") LOG_DIR="$HOME/docker-logs" LOG_FILE="$LOG_DIR/$TIMESTAMP.log" mkdir -p "$LOG_DIR" echo "before pruning:" >> "$LOG_FILE" df -h | sed -n '4p' >> "$LOG_FILE" 2>&1 echo "Running system prune at $TIMESTAMP" >> "$LOG_FILE" sudo docker system prune -a -f >> "$LOG_FILE" 2>&1 echo "Completed system prune at $(date +"%d-%m-%Y_%H-%M-%S")" >> "$LOG_FILE" echo "after pruning:" >> "$LOG_FILE" df -h | sed -n '4p' >> "$LOG_FILE" 2>&1
Here is another version of script it will show a loader while the script is running in background:
#!/bin/bash animate() { local pid=$1 local delay=0.1 local spin='-\|/' local processing_text=$2 while ps a | awk '{print $1}' | grep -q "$pid"; do printf '%s %c\r' "$processing_text" "$spin" spin=${spin#?}${spin%???} sleep "$delay" done printf '\r%s\n' "$processing_text" # Print the processing text on a new line } TIMESTAMP=$(date +"%d-%m-%Y_%H-%M-%S") LOG_DIR="$HOME/docker-logs" LOG_FILE="$LOG_DIR/$TIMESTAMP.log" mkdir -p "$LOG_DIR" # Start loading animation in the background animate $$ "Processing..." & # Store the PID of the animation process animate_pid=$! # Execute the script commands { echo "before pruning:" df -h | sed -n '4p' >>"$LOG_FILE" 2>&1 echo "Running system prune at $TIMESTAMP" sudo docker system prune -a -f echo "Completed system prune at $(date +"%d-%m-%Y_%H-%M-%S")" echo "after pruning:" df -h | sed -n '4p' >>"$LOG_FILE" 2>&1 } >>"$LOG_FILE" 2>&1 # Terminate the animation process kill "$animate_pid" &>/dev/null sleep 1.2 # Print success message on a new line echo "\nSuccess!!"
Got a Questions?
Find us on Socials or Contact us and we’ll get back to you as soon as possible.