簡體   English   中英

停止運行了一定時間的 Docker 容器

[英]Stop a Docker container that's been running for a certain amount of time

我想創建一個 cron 作業,如果 Docker 容器已運行超過 2 小時,它將停止它們。

我可以得到他們開始的時間。

$ docker inspect -f '{{ .State.StartedAt }}' $(docker ps -q)<\/code>

只需要將其與 2 小時前進行比較...

$ date --utc --date="-2 hours" +"%Y-%m-%dT%H:%M:%S.%NZ"<\/code>

...如果它更早停止容器

$ docker stop <<container_id>><\/code>

如何使用 bash 腳本執行此操作?

"

這是一個舊線程,但如果有人正在尋找答案。 以下命令將停止運行超過 2 小時的容器。

docker ps --format="{{.RunningFor}} {{.Names}}"  | grep hours |  awk -F: '{if($1>2)print$1}' | awk ' {print $4} ' | xargs docker stop

說明:

docker ps --format="{{.RunningFor}} {{.Names}}" 

將打印容器名稱和運行周期。

grep hours 

將打印以小時為單位運行的容器。

 awk -F: '{if($1>2)print$1}' 

只會打印運行超過 2 小時的容器。

awk ' {print $4} ' | xargs docker stop

將打印從先前輸出中獲得的容器名稱並將其作為參數傳遞以停止容器。

早在 2013 年,第 1905 期就討論了這個問題

bash 替代方案是:

#!/bin/bash
set -e

to=$1
shift

cont=$(docker run -d "$@")
code=$(timeout "$to" docker wait "$cont" || true)
docker kill $cont &> /dev/null
echo -n 'status: '
if [ -z "$code" ]; then
    echo timeout
else
    echo exited: $code
fi

echo output:
# pipe to sed simply for pretty nice indentation
docker logs $cont | sed 's/^/\t/'

和:

$ docker-run-timeout.sh 10s busybox sh -c 'echo start && sleep 30 && echo finish'
status: timeout
output:
    start

請注意,使用--rm -d 1.13,您可以使用--rm -d運行(請參閱PR 20848 )。

@Siru 的單線很棒,但是我必須更改以下部分才能正確找到超過兩位數天數的容器:

awk -F " " '{if($1>14)print$0}'

@siru 的解決方案激勵我尋找一個選項來了解控制的確切時間,因為running for docker ps 是一個四舍五入的格式化結果而不是精確的:

docker ps -q | xargs docker inspect --format='{{.Id}} {{.State.StartedAt}}' |\
 awk '{convert= "date -d " $2 " +%s"
 current= "date +%s" 
 convert | getline startedAt
 close(convert)
 current | getline now
 close(current)
 if((now-startedAt)/(60*60) > 5) print $1}' |\
 xargs docker rm -f

說明:

第一行將以 ISO 8601 格式傳遞容器 ID 及其開始時間的列表。

然后我們將每個日期轉換為 UNIX 時間,計算與當前時間的增量,並僅將運行時間超過指定時間的行傳遞給docker rm -f

在本例中,所有運行時間超過 6 小時的容器都將被刪除。

我希望在格式字符串的 Go 模板中執行此操作,但我認為我們沒有時間解析包含的函數(可能會成為一個不錯的 PR)。

相反,這是一個利用 date 命令進行時間解析的版本:

#!/bin/sh
# adjust threshold as needed
threshold="2 hours"
# cutoff is seconds since epoc of the threshold time
cutoff="$(date --date="-$threshold" "+%s")"
# loop through the running containers by id
docker container ls -q | while read cid; do
  # retrieve the start time as a string
  startedat="$(docker container inspect "$cid" --format "{{.State.StartedAt}}")"
  # convert to seconds since epoc
  start="$(date --date="$startedat" "+%s")"
  # then we can do a numeric comparison in shell
  if [ "$start" -lt "$cutoff" ]; then
    docker container stop "$cid"
  fi
done

有關使用日期計算偏移量的其他示例,請參閱unix.SE 中的這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM