Skip to content

Instantly share code, notes, and snippets.

@hbi99
Last active July 22, 2025 16:29
Show Gist options
  • Select an option

  • Save hbi99/472e2978381cb3f94f82ff2476a7d92c to your computer and use it in GitHub Desktop.

Select an option

Save hbi99/472e2978381cb3f94f82ff2476a7d92c to your computer and use it in GitHub Desktop.
Cleans up registry - and keeps only the latest tagged version
#!/bin/bash
REGISTRY="example-registry.com"
USER="reg-user"
# List of repositories
REPOSITORIES=(
"repository-1"
"repository-2"
"repository-3"
)
# Function to delete an image using its digest
delete_image() {
local image=$1
local tag=$2
echo "Deleting image: $image:$tag"
digest=$(curl -u $USER:$PWD -I -s -H "Accept: application/vnd.docker.distribution.manifest.v2+json" "http://$REGISTRY:5000/v2/$image/manifests/$tag" | grep Docker-Content-Digest | awk '{print $2}' | tr -d '\r')
if [ -z "$digest" ]; then
echo "Error: Digest not found for image $image:$tag"
return 1
fi
curl -u $USER:$PWD -X DELETE "http://$REGISTRY:5000/v2/$image/manifests/$digest"
}
# Function to get all tags for an image
get_tags() {
local image=$1
curl -u $USER:$PWD -s "http://$REGISTRY:5000/v2/$image/tags/list" | jq -r '.tags[]'
}
# Prompt user for confirmation
echo -n "Enter registry password for user '$USER' to confirm:
"
read -s PWD
if [ "$PWD" ]; then
for image in "${REPOSITORIES[@]}"; do
tags=$(get_tags "$image")
# sort tags and pop last (latest)
sorted=( $( for x in ${tags[@]}; do echo $x; done | sort ) )
unset "sorted[${#sorted[@]}-1]"
for tag in ${sorted[@]}; do
delete_image "$image" "$tag"
done
done
echo "Images deleted successfully."
# Run garbage collection
docker exec -it registry registry garbage-collect /etc/docker/registry/config.yml
# Remove repository folders
for image in "${REPOSITORIES[@]}"; do
docker exec -it registry rm -r "/var/lib/registry/docker/registry/v2/repositories/$image"
echo "Deleted directory for image: $image"
done
# Show final view of the catalog
curl -u $USER:$PWD -X GET http://$REGISTRY:5000/v2/_catalog | jq
else
echo "Operation cancelled."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment