| 1 | #!/bin/bash |
| 2 | |
| 3 | set -euo pipefail |
| 4 | |
| 5 | docker_root=$(docker info -f '{{.DockerRootDir}}') |
| 6 | if [ -z "$docker_root" ]; then |
| 7 | echo "Failed to determine Docker root directory." |
| 8 | exit 1 |
| 9 | fi |
| 10 | echo "Docker root directory: $docker_root" |
| 11 | # Check disk usage of the filesystem where Docker's root directory is located |
| 12 | disk_usage=$(df "$docker_root" | tail -1 | awk '{print $5}' | sed 's/%//') |
| 13 | # Define the threshold |
| 14 | threshold=70 |
| 15 | if [ "$disk_usage" -gt "$threshold" ]; then |
| 16 | echo "Disk usage is above $threshold%. Cleaning up Docker images and volumes..." |
| 17 | # Remove dangling images (those that are not tagged and not used by any container) |
| 18 | docker image prune -f |
| 19 | # Remove unused volumes / force the system prune for old images as well. |
| 20 | docker volume prune -f && docker system prune --force --filter "until=24h" --all |
| 21 | echo "Docker images and volumes cleanup completed." |
| 22 | else |
| 23 | echo "Disk usage is below $threshold%. No cleanup needed." |
| 24 | fi |