简体   繁体   English

杀死所有具有给定镜像名称的容器,除了最近的一个

[英]Kill all containers with given image name EXCEPT the most recent one

I have a process on a cron job that starts every 30 minutes.我有一个每 30 分钟启动一次的 cron 作业进程。 The process starts a docker container with a given image name.该过程使用给定的图像名称启动 docker 容器。 Sometimes the process running in the docker container gets bogged down and then I end up with several docker containers running;有时在 docker 容器中运行的进程会陷入困境,然后我最终会运行几个 docker 容器; 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?"对于这个问题,我想知道“有没有办法杀死所有正在运行的 docker 容器,除了最后一个开始运行的容器?”

I looked at this SO question and it shows how to kill all of them.我查看了这个SO question ,它显示了如何杀死所有这些问题。 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.我在 Linux 工作,我愿意编写一个 shell 脚本,可以在需要时调用它来执行此操作。

Use the docker ps -l and -f flags for this.为此,请使用 docker ps -l 和 -f 标志。 eg:例如:

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. -f 祖先指定要过滤的图像,-l 显示指定的祖先过滤器的最新容器。

We can then use this along with awk to get a list of the container ids that aren't the latest:然后我们可以将它与 awk 一起使用来获取不是最新的容器 id 的列表:

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.我们在 awk 中将 docker ps 命令作为两个单独的输入处理两次,第一个具有最新的、过滤的 output,第二个具有给定过滤器的所有容器。 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.使用第一个输入 (NR==FNR) 我们错过了 header (FNR>1) 并将变量 dockid 设置为容器 ID(第一个空格分隔字段)然后使用第二个输入,我们打印不同的容器 ID作为dockid,同时折扣任何标题。

Putting this together with docker rm:将其与 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM