How can I delete Docker images by tag, preferably

2020-02-16 07:24发布

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?

标签: docker
6条回答
▲ chillily
2楼-- · 2020-02-16 07:30

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).

查看更多
劫难
3楼-- · 2020-02-16 07:31

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.
查看更多
欢心
4楼-- · 2020-02-16 07:32

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

查看更多
地球回转人心会变
5楼-- · 2020-02-16 07:40

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)
查看更多
6楼-- · 2020-02-16 07:49

Fun with bash:

docker rmi $(docker images | grep stuff_ | tr -s ' ' | cut -d ' ' -f 3)
查看更多
该账号已被封号
7楼-- · 2020-02-16 07:53

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}')
查看更多
登录 后发表回答