Home > Back-end >  Delete docker images with same name
Delete docker images with same name

Time:03-29

Server storing multiple docker images with same name but with different tags, I am finding the good command which will search docker images with same name, but with different tags, and delete all, saving only the newest. Example.

TestImage:v1
TestImage:v2
TestImage:v3
TestImage:v4

The command will delete all images which have name "TestImage" but save TestImage:v4 (which is newest by date).

The actual command .

CodePudding user response:

Provided you have the docker cli installed, the following should work:

image_ids=$(docker image ls "$name" -q | tail -n  2 | xargs)
docker image rm "$image_ids"

The first command loads all local images with the given name. Using the -q flag means that only the image ids are being outputted.
the tail program then skips the first one of these ids (in other words, starts reading at line 2). Since images are sorted from new to old, this means the newest image is skipped.
The xargs then brings all the outputted ids into the same line, so that docker can interpret them easily.

The ids obtained in that step may look something like this:

ae3c4906b72c 650d66a00131 18cac929dc4f

docker image rm will then remove all images with these ids.

  • Related