Compute the total memory used by Docker containers in Bash
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
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"}'
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 "$@"