48 lines
1.8 KiB
Bash
48 lines
1.8 KiB
Bash
#!/usr/bin/env bash
|
|
# Reclaim Docker's unused cache so host storage stays bounded.
|
|
#
|
|
# Modes:
|
|
# (default) — post-deploy cleanup (safe, fast):
|
|
# - Build cache older than 72h, capped at 4 GB max used space.
|
|
# - Unreferenced images older than 7 days (keeps rollback images around).
|
|
# - Stopped containers older than 24h.
|
|
# --force — emergency mode ("never let the disk max out"): drops everything
|
|
# with no age windows:
|
|
# - ALL unreferenced build cache,
|
|
# - ALL unreferenced images (no age grace),
|
|
# - ALL stopped containers.
|
|
#
|
|
# Volumes are NEVER pruned in either mode: mariadb-turbo-data is a database.
|
|
# Idempotent; exits 0 when Docker is unavailable.
|
|
set -Eeuo pipefail
|
|
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
LOG_DIR="${LOG_DIR:-$DIR/logs}"
|
|
mkdir -p "$LOG_DIR"
|
|
LOG_FILE="$LOG_DIR/docker-prune.log"
|
|
now() { date '+%Y-%m-%d %H:%M:%S'; }
|
|
|
|
FORCE=0
|
|
if [[ "${1:-}" == "--force" ]]; then
|
|
FORCE=1
|
|
fi
|
|
|
|
command -v docker >/dev/null 2>&1 || {
|
|
printf '[%s] docker CLI unavailable; nothing to prune\n' "$(now)" >>"$LOG_FILE"
|
|
exit 0
|
|
}
|
|
|
|
printf '\n[%s] === docker prune start%s ===\n' "$(now)" "$( (( FORCE )) && printf ' (FORCE)' )" >>"$LOG_FILE"
|
|
docker system df >>"$LOG_FILE" 2>&1 || true
|
|
|
|
if (( FORCE )); then
|
|
docker builder prune -af >>"$LOG_FILE" 2>&1 || true
|
|
docker image prune -af >>"$LOG_FILE" 2>&1 || true
|
|
docker container prune -f >>"$LOG_FILE" 2>&1 || true
|
|
else
|
|
docker builder prune -af --filter "until=72h" --max-used-space=4g >>"$LOG_FILE" 2>&1 || true
|
|
docker image prune -af --filter "until=168h" >>"$LOG_FILE" 2>&1 || true
|
|
docker container prune -f --filter "until=24h" >>"$LOG_FILE" 2>&1 || true
|
|
fi
|
|
|
|
printf '\n[%s] === docker prune complete%s ===\n' "$(now)" "$( (( FORCE )) && printf ' (FORCE)' )" >>"$LOG_FILE"
|
|
docker system df >>"$LOG_FILE" 2>&1 || true |