Kyle Banks

Docker Stats (Memory, CPU, etc.) in JSON Format

Written by @kylewbanks on Feb 9, 2017.

docker stats is a useful command to get an overview of the resource usage of your running Docker containers. For instance, you can see the current memory, CPU, and network usage of your containers.

This is all well and good, but while waiting for some long running docker tasks to complete, I began to think it would be cool to visualize the memory and CPU usage as the container is running. Luckily, since Docker is written in Go, it supports the wonderfully simplistic text/template package to customize output.

Here’s how you can get the current status of your Docker container as a JSON object:

docker stats --no-stream --format \
    "{\"container\":\"{{ .Container }}\",\"memory\":{\"raw\":\"{{ .MemUsage }}\",\"percent\":\"{{ .MemPerc }}\"},\"cpu\":\"{{ .CPUPerc }}\"}"

Here I only use a couple of the statistics you can retrieve. For a full list, take a look at the Docker stats.go source code.

And here’s a look at the output:

{  
   "container": "7e9d088ecca3",
   "memory": {  
      "raw": "239.4 MiB / 7.787 GiB",
      "percent": "3.00%"
   },
   "cpu": "80.08%"
}

With this, it becomes trivial to write up a script to monitor statistics of your Docker containers and visualize the results as needed.

Update

I recent released a small Go package called dockerstats to monitor your Docker containers. It also comes with a small example program that monitors your container statistics and writes them out to a file, allowing you to make comparisons between container executions.

Let me know if this post was helpful on Twitter @kylewbanks or down below, and follow me to keep up with future posts!