dockerubuntudocker-image

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?


Solution

  • 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.