Cleanup docker
#!/bin/bash
# Get the current date in seconds since the epoch
NOW=$(date +%s)
# Define the threshold for 6 months in seconds (approximately)
SIX_MONTHS=15552000
# List all containers with status exited
docker ps -a --filter "status=exited" --format "{{.ID}}" | while read -r id; do
# Get the ExitTime in RFC3339 format using docker inspect
exit_time=$(docker inspect --format='{{.State.FinishedAt}}' "$id")
# Skip if exit_time is null
if [ "$exit_time" == "" ] || [ "$exit_time" == "null" ]; then
continue
fi
# Convert the container's exit time to seconds since epoch
container_exit_date=$(date -d "$exit_time" +%s)
# Calculate how long ago the container exited
duration=$((NOW - container_exit_date))
# Check if the container exited more than 6 months ago
if [ "$duration" -gt "$SIX_MONTHS" ]; then
echo "Removing container $id (exited on $exit_time)"
docker rm "$id"
fi
done
# Now prune all unused images
docker image prune -a -f
Meta
Author: Philip W. Sorst
Created: 2024-11-03 16:11
Updated: 2024-11-03 16:11