ci(docker): prune old image versions

This commit is contained in:
2026-07-09 10:23:34 +08:00
parent fc92c3a5d5
commit e8b745d991
6 changed files with 255 additions and 35 deletions
+36 -1
View File
@@ -7,9 +7,10 @@ ENV_FILE="${2:-}"
HOST_PORT="${3:-}"
CONTAINER_NAME="${4:-}"
PROJECT_NAME="${5:-}"
SERVER_RETAIN_COUNT="${6:-0}"
if [ -z "$IMAGE" ] || [ -z "$ENV_FILE" ] || [ -z "$HOST_PORT" ] || [ -z "$CONTAINER_NAME" ] || [ -z "$PROJECT_NAME" ]; then
echo "Usage: $0 <image> <env-file> <host-port> <container-name> <compose-project-name>" >&2
echo "Usage: $0 <image> <env-file> <host-port> <container-name> <compose-project-name> [server-retain-count]" >&2
exit 64
fi
@@ -50,4 +51,38 @@ echo "=== compose project: $COMPOSE_PROJECT_NAME ==="
docker image prune -f
prune_project_images() {
local retain_count="$1"
if ! [[ "$retain_count" =~ ^[0-9]+$ ]] || [ "$retain_count" -le 0 ]; then
return 0
fi
local image_repo="${IMAGE%%:*}"
local image_tag="${IMAGE##*:}"
local tag_prefix="${image_tag%%-*}-"
if [ -z "$image_repo" ] || [ "$image_repo" = "$IMAGE" ] || [ -z "$tag_prefix" ]; then
echo "Skip project image prune: could not parse image repo/tag from $IMAGE"
return 0
fi
echo "=== prune local project images: keep $retain_count for $tag_prefix ==="
docker image ls "$image_repo" \
--format '{{.Repository}}:{{.Tag}} {{.CreatedAt}}' \
| awk -v prefix="$tag_prefix" '$1 ~ ":" prefix && $1 !~ /-latest$/ { print }' \
| sort -k2,3r \
| awk -v keep="$retain_count" 'NR > keep { print $1 }' \
| while IFS= read -r old_image; do
[ -n "$old_image" ] || continue
if [ "$old_image" = "$IMAGE" ]; then
continue
fi
echo "Removing local image: $old_image"
docker image rm "$old_image" || true
done
}
prune_project_images "$SERVER_RETAIN_COUNT"
echo "=== deploy done ==="