How to determine what containers use the docker volume?

DockerDocker VolumeDocker Container

Docker Problem Overview


Suppose I have a volume and I know its name or id.

I want to determine the list of containers (their names or ids) that use the volume.

What commands can I use to retrieve this information?

I thought it can be stored in the output of docker volume inspect <id> command but it gives me nothing useful other than the mount point ("/var/lib/docker/volumes/<id>").

Docker Solutions


Solution 1 - Docker

docker ps can filter by volume to show all of the containers that mount a given volume:

docker ps -a --filter volume=VOLUME_NAME_OR_MOUNT_POINT

Reference: https://docs.docker.com/engine/reference/commandline/ps/#filtering

Solution 2 - Docker

This is related to jwodder suggestion, if of any help to someone. It basically gives the summary of all the volumes, in case you have more than a couple and are not sure, which is which.

import io
import subprocess
import pandas as pd


results = subprocess.run('docker volume ls', capture_output=True, text=True)

df = pd.read_csv(io.StringIO(results.stdout),
                 encoding='utf8',
                 sep="    ",
                 engine='python')

for i, row in df.iterrows():
    print(i, row['VOLUME NAME'])
    print('-' * 20)
    cmd = ['docker', 'ps', '-a', '--filter', f'volume={row["VOLUME NAME"]}']
    print(subprocess.run(cmd,
           capture_output=True, text=True).stdout)
    print()

Solution 3 - Docker

The script below will show each volume with the container(s) using it:

#!/bin/sh

volumes=$(docker volume ls  --format '{{.Name}}')

for volume in $volumes
do
  echo $volume
  docker ps -a --filter volume="$volume"  --format '{{.Names}}' | sed 's/^/  /'
done

Listing volumes by container is slightly trickier so it's an exercise for the reader but the above should suffice unless you have many containers/volumes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongerichhomeView Question on Stackoverflow
Solution 1 - DockerjwodderView Answer on Stackoverflow
Solution 2 - DockerOrenView Answer on Stackoverflow
Solution 3 - DockerThickycatView Answer on Stackoverflow