Nicolas Henneaux
Nicolas Henneaux

Reputation: 12205

Compute the total memory used by Docker containers in Bash

How to compute in one Bash command line the total memory used by Docker containers running on the local Docker engine?

Upvotes: 20

Views: 7528

Answers (3)

Tom Kay
Tom Kay

Reputation: 1551

tl;dr

docker stats --no-stream --format '{{.MemUsage}}' | awk '{print $1}' | sed 's/GiB/ * 1024/;s/MiB//;s/KiB/ \/ 1024/' | bc -l | awk '{s+=$1} END {print s}'

Breaking this down:

docker stats --no-stream --format '{{.MemUsage}}' - Get only the memory usage

awk '{print $1}' - Strip the total memory from each line

sed 's/GiB/ * 1024/;s/MiB//;s/KiB/ \/ 1024/' - Normalize values into MiB

bc -l - Run calculations

awk '{s+=$1} END {print s}' - Sum all lines

Upvotes: 6

user3552017
user3552017

Reputation: 51

To get total memory regardless of container size --KiB, MiB, or GiB

docker stats --no-stream --format 'table {{.MemUsage}}' | sed -n '1!p' | cut -d '/' -f1 | sed 's/GiB/ * 1024 MiB/;s/MiB/ * 1024 KiB/;s/KiB/ * 1024/; s/$/ +\\/; $a0' | bc | numfmt --to=iec-i --suffix=B "$@"

Upvotes: 4

Nicolas Henneaux
Nicolas Henneaux

Reputation: 12205

I use the following command to compute the total memory used in MB.

docker stats --no-stream --format 'table {{.MemUsage}}' | sed 's/[A-Za-z]*//g' | awk '{sum += $1} END {print sum "MB"}'

or if any are larger than 1GiB

docker stats --no-stream --format 'table {{.MemUsage}}' | sed 's/\.\([0-9]*\)GiB/\1MiB/g' | sed 's/[A-Za-z]*//g' | awk '{sum += $1} END {print sum "MB"}'

Upvotes: 27

Related Questions