240

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?

Akshay barahate
  • 649
  • 8
  • 23
Collin Estes
  • 5,577
  • 7
  • 51
  • 71

21 Answers21

329

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • This is great. My problem after that is when removing the containers, since they are sttoped, they are not returned by docker pd. Any clues of how to do it? – kiril Dec 11 '15 at 09:40
  • @kiril stopped container are returned by `ps -a`. *Removed* containers... well they are removed, they do not exist anymore. – VonC Dec 11 '15 at 09:43
  • 1
    Thanks, I didn't realize stop returns the containers as well. So chaining stop and rm will do the job: docker rm $(docker stop $(docker ps -a -q --filter="name=")) – kiril Dec 11 '15 at 10:26
  • @kiril That is the idea, yes. – VonC Dec 11 '15 at 10:27
  • This does not work if you only know the repository (ie: `my_image`) and not the specific image tag (ie: `my_image:some_specific_tag`). The ancestor option does not support wildcard matching. – Alex Jansen Jul 30 '21 at 01:44
  • 1
    @AlexJansen Interesting feedback, thank you. I did not manage to make your solution work when I have multiple container running from the same image, so I referenced your solution in my answer, and added my own implementation, based on yours. Again, thank you. – VonC Jul 30 '21 at 06:17
  • Looks good. Turning it into a function seems like an improvement as well. – Alex Jansen Jul 30 '21 at 06:47
  • @AlexJansen Yes, I am way too lazy to remember all those commands ;) – VonC Jul 30 '21 at 06:48
107

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

docker stop $(docker ps -q --filter ancestor=<image-name> )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Koekiebox
  • 5,793
  • 14
  • 53
  • 88
  • 1
    Interesting use of ancestor there (https://docs.docker.com/engine/reference/commandline/ps/#filtering). +1 – VonC Jan 20 '16 at 12:14
  • 1
    Works on Docker Terminal for Windows as well. – Koekiebox Jun 14 '16 at 13:34
  • 1
    This does not work for me in Ubuntu 20.04 with Docker version 20.10.5, build 55c4c88. the command `docker ps -q --filter ancestor=` returns nothing, while the command `docker ps -a -q --filter ancestor=` from the accepted answer returns the containers ids that are matching. – JoanComasFdz Apr 01 '21 at 13:10
  • This answer also doesn't work if you only know the repository (ie: `my_image`) and not the specific image tag (ie: `my_image:some_specific_tag`). The ancestor option does not support wildcard matching. – Alex Jansen Jul 30 '21 at 01:46
  • add `-a` option to remove all containers including stopped ones – sprutex Apr 14 '22 at 10:46
71

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Javier Sánchez
  • 984
  • 6
  • 7
  • I really like this solution. Is there a better way to build, stop/remove and then run a container than this? `sudo docker build . -t && sudo docker stop || true && sudo docker run -d --rm --name ` – melanke Sep 12 '19 at 14:59
20

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}')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ArgonQQ
  • 1,917
  • 1
  • 11
  • 12
10

Two ways to stop running a container:

1. $docker stop container_ID

2. $docker kill container_ID

You can get running containers using the following command:

$docker ps

Following links for more information:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kalyani chaudhari
  • 7,515
  • 3
  • 24
  • 21
9

This will only stop all containers with image = "yourImgName" :

sudo docker stop $(sudo docker ps | grep "yourImgName" | cut -d " " -f 1)

This will stop and remove all containers with image = "yourImgName" :

sudo docker rm $(sudo docker stop $(sudo docker ps -a | grep "yourImgName" | cut -d " " -f 1))
MohaDarkness
  • 91
  • 1
  • 3
6

I made a /usr/local/bin/docker.stop that takes in the image name (assumes you only have one running).

docker stop $(docker ps -q -f "name=$1")
AmanicA
  • 4,659
  • 1
  • 34
  • 49
4

Stop docker container by image name:

imagename='mydockerimage'
docker stop $(docker ps | awk '{split($2,image,":"); print $1, image[1]}' | awk -v image=$imagename '$2 == image {print $1}')

Stop docker container by image name and tag:

imagename='mydockerimage:latest'
docker stop $(docker ps | awk -v image=$imagename '$2 == image {print $1}')

If you created the image, you can add a label to it and filter running containers by label

docker ps -q --filter "label=image=$image"

Unreliable methods

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

does not always work

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

filters by container name, not image name

docker ps | grep <image-name> | awk '{print $1}'

is problematic since the image name may appear in other columns for other images

Jay
  • 9,314
  • 7
  • 33
  • 40
  • This is the first answer here which actually supports stopping containers based on the image name. The other answers require you to know the image tag as well. – Alex Jansen Jul 30 '21 at 01:52
3

list all containers with info and ID

docker ps

docker stop CONTAINER ID
Muhammed Moussa
  • 4,589
  • 33
  • 27
2

For Docker version 18.09.0 I found that format flag won't be needed

docker rm $(docker stop $(docker ps -a -q -f ancestor=<image-name>))
ankitj
  • 335
  • 4
  • 13
2

Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:

dockstop() {
  docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}

Then in your command line, simply do dockstop myImageName and it will stop and remove all containers that were started from an image called myImageName.

Antoine Jaussoin
  • 5,002
  • 4
  • 28
  • 39
1

I was trying to wrap my Docker commands in gulp tasks and realised that you can do the following:

docker stop container-name
docker rm container-name

This might not work for scenarios where you have multiple containers with the same name (if that's possible), but for my use case it was perfect.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Gaunt
  • 9,434
  • 3
  • 36
  • 57
1

In my case --filter ancestor=<image-name> was not working, so the following command cleaned up the Docker container for me:

docker rm $(docker stop $(docker ps -a -q --filter "name=container_name_here" --format="{{.ID}}"))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alexey
  • 1,914
  • 16
  • 13
1

use: docker container stop $(docker container ls -q --filter ancestor=mongo)

    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
    d394144acf3a        mongo               "docker-entrypoint.s…"   15 seconds ago      Up 14 seconds       0.0.0.0:27017->27017/tcp   magical_nobel
    (base) :~ user$ docker container stop $(docker container ls -q --filter ancestor=mongo)
    d394144acf3a
    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    (base) :~ user$
ASH
  • 980
  • 1
  • 9
  • 22
1

This is my script to rebuild docker container, stop and start it again

docker pull [registry]/[image]:latest
docker build --no-cache -t [localregistry]/[localimagename]:latest -f compose.yaml context/
docker ps --no-trunc | grep [localimagename] | awk '{print $1}' | xargs docker stop
docker run -d -p 8111:80 [localregistry]/[localimagename]:latest

note --no-trunc argument which shows the image name or other info in full lenght in the output

Scholtz
  • 2,878
  • 2
  • 23
  • 23
1

Here's a concise command which doesn't require you to specify the image tag (as most of these answers do):

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

Alex Jansen
  • 1,455
  • 5
  • 18
  • 34
  • Are you sure about those double quotes in `docker stop "$(...)"`? Whenever I try your option, I get: `Error response from daemon: No such container: 804d82eebf40 36adf6b2be3d d288a5f934dd`. Without the double quotes though, it does work. – VonC Jul 30 '21 at 06:32
  • It does look like the double-quotes were a mistake. I just tested without them and now it works. It doesn't look like I needed the `tr` call either. Do you remember the specific situation where it was needed? – Alex Jansen Jul 30 '21 at 06:36
  • What I do for testing is a bunch of `docker run -d alpine:3.10.3 tail -f /dev/null`. Then I try to stop them all in one go. – VonC Jul 30 '21 at 06:39
  • Do you mean images or containers? I tested with multiple containers from the same image and was able to stop them all at once. I imagine you'd have to run the command multiple times for multiple images. – Alex Jansen Jul 30 '21 at 06:39
  • 1
    Got it: my version used `print $1` instead of `print$1`: with `print$1`, no need for `tr`. Thank you again. I will fix my answer. – VonC Jul 30 '21 at 06:42
0
docker stop $(docker ps -a | grep "zalenium")
docker rm $(docker ps -a | grep "zalenium")

This should be enough.

Berkay Kirmizioglu
  • 1,134
  • 1
  • 11
  • 23
0

If you want to prefer a simple AWK approach, here Is my take:

docker rm -f $(docker ps | awk '{ if($2 == "<your image name>") { print $NF}}')

$(docker ps | awk '{ if($2 == "<your image name>") { print $NF}}') - prints the docker container names based on input image

docker ps - list all containers

awk '{ if($2 == "<your-image-name>") { print $NF}}' - The second parsed column of docker ps gives the image name. Comparing it with your image name will execute print $NF which prints the container name.

docker rm -f removes the containers

For example, removing all running containers of ubuntu image, can be done simply as:

docker rm -f $(docker ps | awk '{ if($2 == "ubuntu:latest") { print $NF}}')

PS: Remember to include the image tag in AWK, since it's a equal comparator.

ashutosh
  • 1,192
  • 5
  • 22
  • 46
0

if you know a part of the container name you can use AWK with docker as following :

  CONTAINER_IDS=$(docker ps -a | awk '($2 ~ /container.*/) {print $1}')
  if [ -z "$CONTAINER_IDS" -o "$CONTAINER_IDS" == " " ]; then
    echo "No containers available for deletion"
  else
    docker rm -f $CONTAINER_IDS
  fi
arwa
  • 31
  • 3
0
image: docker
services:
  - docker:dind
stages:
  - deploy
step-deploy-prod:
  stage: deploy
  tags:
  - docker
  script:
    - container_id=$(docker ps -q -a -f status=running --filter name=todoapp)
    - if [ -n "$container_id" ]; then 
        docker stop $container_id; 
        docker rm -f $container_id;
      fi
    - container_id=$(docker ps -q -a -f status=exited --filter name=todoapp)
    - if [ -n "$container_id" ]; then 
        docker rm -f $container_id;
      fi
    - docker build -t app/creative .
    - docker run -d -p 8081:80 --name todoapp app/creative

First, check for a running container with the command docker ps -q -a -f status=running --filter name=todoapp , if it finds one it stops and deletes the running container then check for any containers that are stopped and have the name todoapp using the command docker ps -q -a -f status=exited --filter name=todoapp, then it will remove the container if it's found. Then it will build a new image and start a new container with the new build image.

As I have found out, if you stop the container, it can't be found with docker rm just incase anyone stumbles across this if you are wanting to replace a newly deployed image via gitlab-ci

There is an option in docker ps command -f status=exited which shows all the containers which are in stopped state.

container_id=$(docker ps -q -a -f status=exited --filter name=todoapp)

This command would only return container ids that are stopped and has name todoapp

Also, a better way to remove the stopped container is by using the -f or --force option with the docker rm command. This option will remove the container even if it is in a stopped state.

Steven Mcsorley
  • 81
  • 1
  • 1
  • 7
-4

You can use the ps command to take a look at the running containers:

docker ps -a

From there you should see the name of your container along with the container ID that you're looking for. Here's more information about docker ps.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131