I'm trying to estimate the bandwidth of all my running dockers' container on my server.
I tried using Docker API v1.41. With a php:8-fpm running in a container.
function GetData($url)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://host.docker.internal:2375/v1.41/containers/$url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$res = json_decode(curl_exec($curl), true);
curl_close($curl);
return $res;
}
// fetch all container
$data = GetData('json');
$total = 0;
foreach ($data as $container)
{
$id = $container["Id"];
$url = "$id/stats?one-shot=true&stream=false";
// fetch container stats
$stat = GetData($url);
$networks = $stat['networks'];
// sum all i/o bytes
foreach ($networks as $nt)
{
$total += $nt["rx_bytes"] + $nt["tx_bytes"];
}
}
// get previous reading
$filename = getcwd() . "/previous.txt";
$bandwidth = 0;
if (file_exists($filename))
{
$previoustime = filemtime($filename);
$previoustx = intval(file_get_contents($filename));
$newtime = time();
$elapsed = ($newtime - $previoustime);
if ($elapsed > 0)
{
$bandwidth = max(0,round(($total - $previoustx) / $elapsed));
}
}
file_put_contents(getcwd() . "/previous.txt", $total);
echo json_encode(array(
"version" =>"v1.41",
"bandwidth" => $bandwidth
));
I call this API every 10 seconds.
It works fine and bandwidth seem quite accurate. However, I sometime have some crazy big bandwidth values (ex : 203 262 380 683 B/s.) and I don't know where this come from.
The big values appear totally randomly once every 10 to 500 call, regardless of whether I'm using any bandwidth.
I don't know if PHP int are big enough to handle this kind of value, or if there is an error in my code.
Here is the docker API reference: https://docs.docker.com/engine/api/v1.41/#tag/Container/operation/ContainerStats
I tried reproducing the issue on my computer windows docker but I never had "big" value. Even by spam calling the API. I have no clue on where those values come from.