Docker n 秒期间的统计数据

Docker stats for n seconds period

我 运行 docker stats $CONTAINER_ID 来自 shell 脚本来监控我的 Docker 容器内存和 CPU 在 1 小时内的使用情况。我有下面的 shell 脚本。

#!/bin/sh

# First, start the container
CONTAINER_ID=abcadsasdasd

# Then start watching that it's running (with inspect)
while [ "$(docker inspect -f {{.State.Running}} $CONTAINER_ID 2>/dev/null)" = "true" ]; do
    # And while it's running, check stats
    #docker stats $CONTAINER_ID 2>&1 | tee ""
    docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}" $CONTAINER_ID 2>&1 | tee ""
    sleep 5
done

运行 很好。但是,似乎每秒都是 运行 。我需要它每 5 秒输出一次。我发现没有像使用 docker stats 命令指定时间段这样的选项。请求一些建议来实现它。看来 sleep 5 没有任何效果。

编辑

即使有 1 秒的延迟,我预计我的日志文件中有 60 行,如果有 5 秒,我预计 1 分钟内有 12 行。但是,我在 1 分钟内接近 150 行。

docker stats $container不会在运行时退出,所以你的sleep 5没有机会执行。

对于你来说,你应该使用下一个:

--no-stream       Disable streaming stats and only pull the first result

然后,您可以使用类似于下一个伪造代码的东西来控制速率:

while xxx; do
    docker stats $container --no-stream
    sleep 5
done

不休眠,只需从文件中读取当前值 ($1) 并在您选择的每个时间段取平均值:

#!/bin/bash

multiLine="";
format="table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}";
docker stats --all --format "$format" --no-trunc | (while read line; do
    sedLine=$(echo "$line" | sed "s/^.*name.*cpu.*mem.*$/_divider_/i")
    if [ "$sedLine" != "_divider_" ];
    then
        multiLine="${multiLine}"'\n'"${line}";
    else
        echo -e $multiLine > ;
        multiLine="";
    fi;
done);