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 )

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}'
  • 1
    My vote for piping grep and cut where awk is the perfect tool for the task :) – Tensibai Jan 29 '19 at 21:40
  • i was wondering why you did the --format as your awk works without it then i realised that it makes things future proof to changes in the default docker ps output. – simbo1905 Jan 31 '19 at 6:51
  • 1
    Exactly @simbo1905. You can't safely rely on the default format: without an explicit format, the output of docker ps is not only version-dependant (I assume) but also site-specific since it can be configured system-wide using the psFormat configuration option (docs.docker.com/engine/reference/commandline/cli/…). – Sylvain Leroux Jan 31 '19 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.