Questions:
How can I remove all docker containers based on a docker image name. I do not wish to remove all available containers, only the those which are based on particular image. For example I would like to remove all containers based on image centos:7
.
Answer:
To remove all docker containers based on centos:7
run the following linux command:
# docker ps -a | awk '{ print $1,$2 }' | grep centos:7 | awk '{print $1 }' | xargs -I {} docker rm {}
The full workout and piping explanations can be found below.
First, we need to get all container ID’s:
# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 16ef47387cbd fedora:21 "/bin/bash" 5 hours ago Exited (0) 5 hours ago romantic_heisenberg 6ae3e3870739 centos:7 "/bin/bash" 5 hours ago Exited (0) 5 hours ago clever_rosalind effd4037ab74 centos:7 "/bin/bash" 5 hours ago Exited (0) 5 hours ago backstabbing_almeida 72c89af47615 debian:8 "/bin/bash" 5 hours ago Exited (0) 5 hours ago berserk_pasteur 195c78f3eb0b debian:8 "/bin/bash" 5 hours ago Exited (0) 5 hours ago cocky_yonath f060a5bfdb11 debian:8 "/bin/bash" 5 hours ago Exited (0) 5 hours ago insane_galileo
To avoid the confusion between image and container name we can keep only CONTAINER ID
and IMAGE
columns:
# docker ps -a | awk '{ print $1,$2 }' CONTAINER ID 16ef47387cbd fedora:21 6ae3e3870739 centos:7 effd4037ab74 centos:7 72c89af47615 debian:8 195c78f3eb0b debian:8 f060a5bfdb11 debian:8
Next, we can pipe the above output to the grep
command to filter only those containers which are based on an certain image name. For example let’s filter all containers based on centos:7
image:
# docker ps -a | awk '{ print $1,$2 }' | grep centos:7 6ae3e3870739 centos:7 effd4037ab74 centos:7
At this point we are only interested in CONTAINER ID
:
# docker ps -a | awk '{ print $1,$2 }' | grep centos:7 | awk '{print $1 }' 6ae3e3870739 effd4037ab74
Lastly, we can use xargs
and remove remaining container ID’s:
# docker ps -a | awk '{ print $1,$2 }' | grep centos:7 | awk '{print $1 }' | xargs -I {} docker rm {} 6ae3e3870739 effd4037ab74