0

I have a process on a cron job that starts every 30 minutes. The process starts a docker container with a given image name. Sometimes the process running in the docker container gets bogged down and then I end up with several docker containers running; the more I have running the more it gets bogged down. Of course there are underlying issues that are causing this (they're getting worked on too). For THIS question I want to know "Is there a way to kill all of the running docker containers with a given image name EXCEPT for the last container that started running?"

I looked at this SO question and it shows how to kill all of them. Is there a way to exclude the most recent container?

I'm working in Linux and I'd be willing to write a shell script that could be called to do this when needed.

Jed
  • 1,823
  • 4
  • 20
  • 52

1 Answers1

1

Use the docker ps -l and -f flags for this. e.g.:

docker ps -l -f ancestor=grafana/grafana

-f ancestor specifies the image to filter and -l displays the latest container for the ancestor filter specified.

We can then use this along with awk to get a list of the container ids that aren't the latest:

awk 'NR==FNR && FNR>1 { dockid=$1;next } FNR>1 && $1!=dockid { print $1 }' <(docker ps -l -f ancestor=grafana/grafana) <(docker ps -f ancestor=grafana/grafana)

We process the docker ps command twice in awk as two separate inputs, the first having the latest, filtered output and the second all the containers with the given filter. With the first input (NR==FNR) we miss the header (FNR>1) and set the variable dockid to the container id (first space delimited field) Then with the second input, we print container ids that aren't the same as dockid while at the same time, discounting any headers.

Putting this together with docker rm:

docker rm $(awk 'NR==FNR && FNR>1 { dockid=$1;next } FNR>1 && $1!=dockid { print $1 }' <(docker ps -l -f ancestor=grafana/grafana) <(docker ps -f ancestor=grafana/grafana))
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
  • I'm excited to try this out. – Jed Feb 08 '21 at 16:08
  • This worked great! Only modification was that I was trying to `kill` all of the containers so instead of `docker rm ...` I used `docker kill ...` – Jed Feb 10 '21 at 13:57