HiveBrain v1.2.0
Get Started
← Back to all entries
snippetdockerMinor

How to kill all Docker containers based on a given image?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
killimagealldockerbasedhowcontainersgiven

Problem

How to kill all Docker containers based on a given image?

As an example:

sudo docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
58251f04892a        mariadb:10.4        "docker-entrypoint.s…"   53 seconds ago      Up 52 seconds       3306/tcp                 optimistic_ramanujan
2a08ee7d9afe        mariadb:10.3        "docker-entrypoint.s…"   2 hours ago         Up 2 hours          3306/tcp                 thirsty_taussig
65abd7a3b3e1        mariadb:10.3        "docker-entrypoint.s…"   2 hours ago         Up 2 hours          3306/tcp                 angry_lederberg
32076aa4745e        mariadb:10.3        "docker-entrypoint.s…"   2 hours ago         Up 2 hours          3306/tcp                 distracted_kapitsa


I would like to kill all containers based directly on the mariadb image (ideally, both 10.4 and 10.3).

The following solution does not work since it will kill all containers having mariadb:10.3 as an ancestor--and not only those directly based on that image:

sudo docker kill $( sudo docker ps --filter ancestor=mariadb:10.3 )

Solution

This will do want I want: killing all containers directly based on mariadb regardless of their tag--and without killing containers having mariadb somewhere higher in their ancestor list.

sudo docker kill $(
  sudo docker ps --format '{{.ID}} {{.Image}}' | awk '$2 ~ /^mariadb:/ { print $1}'
)

Code Snippets

sudo docker kill $(
  sudo docker ps --format '{{.ID}} {{.Image}}' | awk '$2 ~ /^mariadb:/ { print $1}'
)

Context

StackExchange DevOps Q#6149, answer score: 4

Revisions (0)

No revisions yet.