Richard
Richard

Reputation: 16762

Stopping docker containers by image name, and don't error if no containers are running

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)

Upvotes: 25

Views: 15956

Answers (1)

Farhad Farahi
Farhad Farahi

Reputation: 39277

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.

Upvotes: 31

Related Questions