Reputation: 1917
I am running docker stats $CONTAINER_ID
from a shell script to monitor my Docker container memory and CPU usage over a period of 1 hour. I have the below shell script.
#!/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
It is running fine. But, it seems it is running at every second. I need that it outputs at every 5 seconds. I found that there is no such option like specifying timeperiod with docker stats command. Request some suggestions to achieve it. It seems sleep 5 is not having any effect.
Edit
Even with 1 second delay, I expected 60 lines in my log file, With 5 seconds, I expected 12 lines over 1 minute period. But, I am getting close to 150 lines for 1 minute.
Upvotes: 7
Views: 7713
Reputation: 195
Without sleep, just read current values from the file ($1) and average them every period you choose:
#!/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);
Upvotes: 2
Reputation: 21123
Easiest approach is to use watch
:
watch -tn5 docker stats --no-stream $CONTAINER_NAME
Upvotes: 6
Reputation: 31674
docker stats $container
won't exit when running, so your sleep 5
don't have chance to execute.
For you, you should use next:
--no-stream Disable streaming stats and only pull the first result
Then, you could use something like next fake code to control the rate:
while xxx; do
docker stats $container --no-stream
sleep 5
done
Upvotes: 4