3

I want to delete the remains of some Docker-operations from within Jenkins.

But somehow the following line does not work...

The issue seems to be with the parenthesis.

Any advice?

if [ docker images -f dangling=true -q|wc -l > 0 ]; then docker rmi --force $(docker images -f dangling=true -q);fi
Jinna Balu
  • 6,747
  • 38
  • 47

4 Answers4

7

Newer versions of Docker now have the system prune command.

To remove dangling images:

$ docker system prune

To remove dangling as well as unused images:

$ docker system prune --all

To prune volumes:

$ docker system prune --volumes

To prune the universe:

$ docker system prune --force --all --volumes
Behrang
  • 46,888
  • 25
  • 118
  • 160
  • `docker system prune` will remove all unused data(all stopped containers, all networks not used, all dangling images...), if only want to remove **dangling** images, `docker image prune` is much better. – Corey Feb 22 '19 at 09:02
  • `docker system prune` is not recomanded when you don't have backup. Use the specific command to specific cases. – Jinna Balu Mar 06 '19 at 18:22
  • Will this remove images of other jobs currently running? – Ray Mar 18 '20 at 19:35
1

docker image prune deletes all dangling images. Docker image prune -a deletes unused images too. This thread explains what dangling and unused images are. In short: Dangling image --> No tag, unused images --> no container attached.

herm
  • 14,613
  • 7
  • 41
  • 62
  • Thanks for your answer, herm. Unfortunately "docker image" does not exist on my machine... Might have been the cleaner, shorter solution... –  Jul 28 '17 at 07:18
  • You mean docker image prune does not exist? That is a relatively new command but docker image ls and others are old. – herm Jul 28 '17 at 07:22
  • Yes it does not exist.... The docker documentation also shows a * beneath docker image. But I don't know what that star means. –  Jul 28 '17 at 07:29
1

Remove Dangling Images

Use -xargs will need --no-run-if-empty (-r) to bypass executing docker rmi with no arguments

docker images --quiet --filter=dangling=true | xargs --no-run-if-empty docker rmi

Use normar bash comand to check and delete

 if docker images -f "dangling=true" | grep ago --quiet; then
    docker rmi -f $(docker images -f "dangling=true" -q)
 fi
Jinna Balu
  • 6,747
  • 38
  • 47
0

I would store the output of the docker images command and then use it:

images=$(docker images -f dangling=true -q); if [[ ${images} ]]; then docker rmi --force ${images}; fi
Andrew
  • 383
  • 3
  • 4