1

I have couple of dangled images (images that appear in docker images with none tag). To clean them, based on LABEL, the usual command is: docker image prune -a --force --filter="label=some-key=some-value".

However, this command doesn't prune dangled images that have container associated. Irrespective of whether the container is started or stopped.

I cannot run docker container prune -f since I don't want to prune all stopped containers. Is there a command to prune images and the containers associated with the image based on image label?

variable
  • 8,262
  • 9
  • 95
  • 215
  • Does this answer your question? [Docker remove TAG images](https://stackoverflow.com/questions/33913020/docker-remove-none-tag-images) – Kulshreshth K May 14 '20 at 12:33
  • Remove only dangling images: ```docker rmi $(docker images --filter "dangling=true" -q --no-trunc)``` – Kulshreshth K May 14 '20 at 12:34
  • You cannot apply rmi on the dangled image which is being used by a container – variable May 14 '20 at 12:36
  • Can you just filter the results from `docker ps -aq` and use that to prune the unneeded containers? Like `docker rm -f $(docker ps -aq --filter=...)`? – superstator May 14 '20 at 17:43
  • Filter based on? And is that a Linux or PowerShell or cross platform command? – variable May 14 '20 at 19:38
  • Whatever you want, I assumed from your question you had some filter in mind. Ex. `docker ps -aq --filter="label=com.docker.compose.service=redis"` gives me all the containers started by compose for redis, ready for pruning – superstator May 14 '20 at 22:03
  • My container doesn't have the label- https://stackoverflow.com/questions/61794023/how-to-use-label-filter-on-intermediate-containers-that-get-created-during-build – variable May 15 '20 at 04:18

1 Answers1

0

Given an image (or images) with a label, you want to delete any containers using that image.

Using xargs and the ancestor filter, you can do that:

docker image ls -q --filter "label=foo=bar" | \
    xargs -I IMG docker ps -aq --filter "ancestor=IMG" | \
    xargs docker rm -fv

It's not exactly "one command" but it should get you where you need to go.

Or Powershell:

@(docker image ls -q --filter "label=foo=bar") | %{&"docker" ps -qa --filter "ancestor=$_"} | %{&"docker" rm -fv $_}
superstator
  • 3,005
  • 1
  • 33
  • 43