23

This question explains how to stop Docker containers started from an image.

But if there are no running containers I get the error docker stop requires a minimum of one argument. Which means I can't run this command in a long .sh script without it breaking.

How do I change these commands to work even if no results are found?

docker stop $(docker ps -q --filter ancestor="imagname")
docker rm `docker ps -aq` &&

(I'm looking for a pure Docker answer if possible, not a bash test, as I'm running my script over ssh so I don't think I have access to normal script tests)

Community
  • 1
  • 1
Richard
  • 14,798
  • 21
  • 70
  • 103
  • 2
    Found the answer in kampde's comment on this blog post: http://blog.yohanliyanage.com/2015/05/docker-clean-up-after-yourself/. Just use xargs with r to ignore empty pipes: **docker ps -q --filter ancestor="imageName" | xargs -r docker stop** – Richard May 12 '16 at 11:43
  • 1
    You should post your solution as an answer and accept it. – Nathan Arthur Sep 12 '16 at 13:53
  • **See Also**: [Stopping Docker containers by image name](https://stackoverflow.com/q/32073971/1366033) – KyleMit Nov 18 '20 at 14:07

1 Answers1

29

Putting this in case we can help others:

To stop containers using specific image:

docker ps -q --filter ancestor="imagename" | xargs -r docker stop

To remove exited containers:

docker rm -v $(docker ps -a -q -f status=exited)

To remove unused images:

docker rmi $(docker images -f "dangling=true" -q)

If you are using a Docker > 1.9:

docker volume rm $(docker volume ls -qf dangling=true)

If you are using Docker <= 1.9, use this instead:

docker run -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/docker:/var/lib/docker --rm martin/docker-cleanup-volumes

Docker 1.13 Update:

To remove unused images:

docker image prune

To remove unused containers:

docker container prune

To remove unused volumes:

docker volume prune

To remove unused networks:

docker network prune

To remove all unused components:

docker system prune

IMPORTANT: Make sure you understand the commands and backup important data before executing this in production.

Farhad Farahi
  • 35,528
  • 7
  • 73
  • 70
  • Trying how to figure out how to use this one on macos `docker ps -q --filter ancestor="imagename" | xargs -r docker stop` which reports `xargs: illegal option -- r usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr] [-L number] [-n number [-x]] [-P maxprocs] [-s size] [utility [argument ...]]` – Matthew James Briggs May 05 '18 at 18:53
  • OK, on mac I guess we can't protect ourselves from the empty strings so easily, just remove `-r` -> `docker ps -q --filter ancestor="web-container" | xargs docker stop` – Matthew James Briggs May 05 '18 at 18:57