How to determine what containers use the docker volume?

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>").


Solution 1:

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:

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()