n 秒期间的 Docker 统计数据

问题描述 投票:0回答:3

我正在从 shell 脚本运行

docker stats $CONTAINER_ID
来监控 1 小时内的 Docker 容器内存和 CPU 使用情况。我有下面的 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 "$1"
    docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}" $CONTAINER_ID 2>&1 | tee "$1"
    sleep 5
done

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

编辑

即使有 1 秒的延迟,我预计日志文件中会有 60 行,在 5 秒内,我预计会在 1 分钟内有 12 行。但是,我 1 分钟的时间已经接近 150 行了。

docker performance memory containers cpu-usage
3个回答
2
投票

在没有睡眠的情况下,只需从文件中读取当前值 ($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 > $1;
        multiLine="";
    fi;
done);

0
投票

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

0
投票

最简单的方法是使用

watch
:

watch -tn5 docker stats --no-stream $CONTAINER_NAME
© www.soinside.com 2019 - 2024. All rights reserved.