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 comma
The previous answers did not work for me, but this did:
docker stop $(docker ps -q --filter ancestor=<image-name> )
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")
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}}"))
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.
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.
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$