Reputation: 11
When using the docker API /containers/{id}/stats I am able to get memory usage from the json file under memory stats.
"memory_stats": {
"stats": {},
"max_usage": 6651904,
"usage": 6537216,
"failcnt": 0,
"limit": 67108864
},
The question is, how do you calculate the percent memory usage for the container from this? Have googled for any documentation on this but not able to get any.
Upvotes: 1
Views: 1734
Reputation: 41
This won't give the same answer as fetched by the Docker stats command. Docker uses multiple combinations to arrive at MEM%, according to my calculations you should take into consideration the cache and active memory as well
The formula would look something like:
def get_mem_perc(stats):
mem_used = stats["memory_stats"]["usage"] - stats["memory_stats"]["stats"]["cache"] + stats["memory_stats"]["stats"]["active_file"]
limit = stats['memory_stats']['limit']
return round(mem_used / limit * 100, 2)
Where stats are the stats value for the entire container
Upvotes: 4
Reputation: 58
docker is open source, which means we can look at the source code :)
Just parse through the json object
and divide usage
by the limit
. Keep in mind, that the limit is the limit of the entire host machine, and exceeding this will result in an OOM kill.
This is also what's displayed when running docker stats
and looking at MEM USAGE / LIMIT
and MEM %
return float(json_object['memory_stats']['usage']) / float(json_object['memory_stats']['limit']) * 100)
Confirmed by looking at the open source repo here
Upvotes: 2