'Selectively prune docker images by tag

If there are multiple image tags for a used image, docker image prune -a will keep the alphabetically last tag. Please see a reproducible example at the bottom.

Is there a way to influence which tags will be kept? Ideally, I would like docker image prune -a to keep all image-tag combinations that are in use (in use includes stopped containers).

Reproducible example (careful as it will delete images from your docker system):

# docker image prune -a keeps hellow-world:x

docker pull hello-world
docker tag hello-world:latest hello-world:x
docker tag hello-world:latest hello-world:a
docker run hello-world:x
docker run hello-world:a
docker image prune -a
# Reset

docker system prune -a
# docker image prune -a keeps hellow-world:z

docker pull hello-world
docker tag hello-world:latest hello-world:x
docker tag hello-world:latest hello-world:z
docker run hello-world:x
docker run hello-world:z
docker image prune -a


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source