Find the container with the largest volume mount

Oct 23, 2023

I had an issue with a server running out of disk-space and wanted to figure out which container has mounted the volume using the most space.

List all the running containers with their mounted volumes using docker ps:

docker ps --format "{{.ID}}: {{.Names}} {{.Mounts}}"

Next I could inspect each container to see the size of the mounted volume.

for container_id in $(docker ps -q); do
  docker inspect --format "{{.ID}}: {{.Name}} {{range .Mounts}}{{.Source}} {{.Destination}} {{end}}" $container_id
done

However, there is no {{.Size}} available directly from docker, so you have to use command line tools get the size in bytes. Also, bind mounts don't make sense to inspect, so use an inclusive to condition to only find "volume" mounts.

#!/usr/env bash

largest_volume_size=0
largest_volume_container=""

for container_id in $(docker ps -q); do
  for volume_name in $(docker inspect -f '{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}' $container_id); do
    volume_size=$(docker volume inspect --format '{{.Size}}' $volume_name)
    if [ $volume_size -gt $largest_volume_size ]; then
      largest_volume_size=$volume_size
      largest_volume_container=$container_id
    fi
  done
done

echo "Container with the largest mounted volume: $largest_volume_container (Volume size: $largest_volume_size bytes)"

If only there was a {{ .Size }} then this could have been solved with osquery.

SELECT c.id as container_id, c.name as container_name, m.source as volume_name, m.type as mount_type
FROM docker_containers c
JOIN docker_container_mounts m ON c.id = m.container_id
WHERE m.type = 'volume';

But — there is no m.size column available.