How can I delete Docker images by tag, preferably

2020-02-16 06:54发布

问题:

I have some automated processes that spew a bunch of Docker images tagged with meaningful labels. The labels follow a structured pattern.

Is there a way to find and delete images by tag? So assume I have images:

REPOSITORY                  TAG
junk/root                   stuff_687805
junk/root                   stuff_384962

Ideally I'd like to be able to do: docker rmi -tag stuff_*

Any good way to simulate that?

回答1:

Fun with bash:

docker rmi $(docker images | grep stuff_ | tr -s ' ' | cut -d ' ' -f 3)


回答2:

Using only docker filtering:

 docker rmi $(docker images --filter=reference="*:stuff_*" -q)
  • reference="*:stuff_*" filter allows you to filter images using a wildcard;
  • -q option is for displaying only image IDs.


回答3:

You can also acomplish it using grep + args + xargs:

docker images | grep "stuff_" | awk '{print $1 ":" $2}' | xargs docker rmi
  • docker images lists all the images
  • grep selects the lines based on the search for "_stuff"
  • awk will print the first and second arguments of those lines (the image name and tag name) with a colon in between
  • xargs will run the command 'docker rmi' using every line returned by awk as it's argument

Note: be careful with the grep search, as it could also match on something besides the tag, so best do a dry run first:

docker images | grep "stuff_" | awk '{print $1 ":" $2}' | xargs -n1 echo
  • xargs -n1 the -n1 flags means xargs will not group the lines returned by awk together, but echo them out one at a time (for better readability)


回答4:

Docker provides some filtering which you can use with labels, but I don't see wildcard support.

docker images -f "label=mylabel=myvalue"

Furthermore to add labels to an image you must add the information to the Dockerfile with a LABEL command. I couldn't find a way to add labels to an image unless you changed the Dockerfile (i.e. couldn't find a commandline option), though you can add them to containers at runtime with --label and --label-file (run docs).



回答5:

docker rmi $(docker images | grep stuff | tr -s ' ' | cut -d ' ' -f 3)



回答6:

I would use the image id to remove the images, the tag being '1.2.3':

docker rmi $(docker images | awk '$2~/1.2.3/{print $3}')


标签: docker