Stopping Docker containers by image name - Ubuntu

On Ubuntu 14.04 (Trusty Tahr) I'm looking for a way to stop a running container and the only information I have is the image name that was used in the Docker run command.

Is there a command to find all the matching running containers that match that image name and stop them?


If you know the image:tag exact container version

Following issue 8959, a good start would be:

docker ps -a -q --filter="name=<containerName>"

Since name refers to the container and not the image name, you would need to use the more recent Docker 1.9 filter ancestor, mentioned in koekiebox's answer.

docker ps -a -q  --filter ancestor=<image-name>

As commented below by kiril, to remove those containers:

stop returns the containers as well.

So chaining stop and rm will do the job:

docker rm $(docker stop $(docker ps -a -q --filter ancestor=<image-name> --format="{{.ID}}"))

If you know only the image name (not image:tag)

As Alex Jansen points out in the comments:

The ancestor option does not support wildcard matching.

Alex proposes a solution, but the one I managed to run, when you have multiple containers running from the same image is (in your ~/.bashrc for instance):

dsi() { docker stop $(docker ps -a | awk -v i="^$1.*" '{if($2~i){print$1}}'); }

Then I just call in my bash session (after sourcing ~/.bashrc):

dsi alpine

And any container running from alpine.*:xxx would stop.

Meaning: any image whose name is starting with alpine.
You might need to tweak the awk -v i="^$1.*" if you want ^$1.* to be more precise.

From there, of course:

drmi() { docker rm $(dsi $1  | tr '\n' ' '); }

And a drmi alpine would stop and remove any alpine:xxx container.


The previous answers did not work for me, but this did:

docker stop $(docker ps -q --filter ancestor=<image-name> )

You could start the container setting a container name:

docker run -d --name <container-name> <image-name>

The same image could be used to spin up multiple containers, so this is a good way to start a container. Then you could use this container-name to stop, attach... the container:

docker exec -it <container-name> bash
docker stop <container-name>
docker rm <container-name>

This code will stop all containers with the image centos:6. I couldn't find an easier solution for that.

docker ps | grep centos:6 | awk '{print $1}' | xargs docker stop

Or even shorter:

docker stop $(docker ps -a | grep centos:6 | awk '{print $1}')