Skip to content

Instantly share code, notes, and snippets.

@natt-v
Last active June 19, 2025 11:00
Show Gist options
  • Select an option

  • Save natt-v/7c5686a7bb90690034cec08cbae5ac83 to your computer and use it in GitHub Desktop.

Select an option

Save natt-v/7c5686a7bb90690034cec08cbae5ac83 to your computer and use it in GitHub Desktop.
Jenkins pipeline script to clean up docker unused containers/images while keeping build cache
pipeline {
agent any
stages {
stage('Docker Cleanup') {
steps {
sh """
echo "\n=== Docker Space Usage Before Cleanup ==="
docker system df
echo "\n=== Current Running Containers ==="
docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"
echo "\n=== Cleaning up ALL stopped containers ==="
# Remove all stopped containers immediately (old deployments)
docker container prune -f
echo "\n=== Cleaning up unused images older than 1 hour ==="
# Aggressive cleanup - only keep very recent images
docker image prune --filter "until=1h" -f
echo "\n=== Cleaning up dangling/untagged images ==="
# Remove all dangling images (old builds)
docker image prune -f
echo "\n=== Cleaning up unused images (not referenced by containers) ==="
# Remove images not used by any container
docker image prune -a --filter "until=1h" -f
echo "\n=== Cleaning up build cache (keeping max 10GB for next builds) ==="
# Keep build cache for faster next builds
docker builder prune --keep-storage 10GB -f
echo "\n=== Cleaning up ALL unused volumes ==="
docker volume prune -f
echo "\n=== Cleaning up unused networks ==="
docker network prune -f
echo "\n=== Docker Space Usage After Cleanup ==="
docker system df
echo "\n=== Active Containers After Cleanup ==="
docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"
echo "\n=== Remaining Images ==="
docker images --format "table {{.Repository}}\\t{{.Tag}}\\t{{.Size}}\\t{{.CreatedAt}}"
echo "\n=== Total Disk Usage ==="
df -h /
"""
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment