DEV Community

Adrien Pétremann
Adrien Pétremann

Posted on

Clean docker volumes

First, we'll take a look at space taken by Docker.

docker system df
Enter fullscreen mode Exit fullscreen mode
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          34        0         12.7GB    12.7GB (100%)
Containers      0         0         0B        0B
Local Volumes   7         0         24.96GB   24.96GB (100%)
Build Cache     0         0         0B        0B
Enter fullscreen mode Exit fullscreen mode

Now, see which volumes uses most space :

docker system df -v
Enter fullscreen mode Exit fullscreen mode
Local Volumes space usage:

VOLUME NAME                                                        LINKS     SIZE
62d5e5e939ff3ac09436e97e57f7ac069a6437505a364c9752765147185bbe4c   0         314.8MB
768a9dd324ac40c20809a3a4a84d1b0e472288bd4a2ff1437a72df2689602738   0         47.73MB
109ee0d2c7319dcaf431397ae2c2cbf31a31df5e7bb2998098d0eefd6c6c4d36   0         47.3MB
897bb1224a20fac27c0a1005b36a1ca700cd5a803cf4f3ab097d46735abcf9b2   0         47.3MB
a917bf9067962cf9365de644f0e07ab08ab10ecd6927bf926cf8b2a586874b53   0         124.2MB
03dac5e5e485efd6408e09866afed5ebf8ed7f7981bd18ab37ec9b04dd485e0e   0         124.2MB
646b44d17a24bb1ccb98462a1fda78dc2da5b5d78339fa05d0b3be4bc7139045   0         124.2MB
Enter fullscreen mode Exit fullscreen mode

Now that you have volume names & size, put all volumes you want to remove in a volumes_to_remove.txt (one per line).

62d5e5e939ff3ac09436e97e57f7ac069a6437505a364c9752765147185bbe4c
768a9dd324ac40c20809a3a4a84d1b0e472288bd4a2ff1437a72df2689602738
109ee0d2c7319dcaf431397ae2c2cbf31a31df5e7bb2998098d0eefd6c6c4d36
897bb1224a20fac27c0a1005b36a1ca700cd5a803cf4f3ab097d46735abcf9b2
a917bf9067962cf9365de644f0e07ab08ab10ecd6927bf926cf8b2a586874b53
Enter fullscreen mode Exit fullscreen mode

Now we'll use a script.sh to parse the .txt file and remove volume one by one :

#!/bin/bash

if [ ! -f "volumes_to_remove.txt" ]; then
    echo "File volumes_to_remove.txt does not exist."
    exit 1
fi

while read -r volume_name; do
    if [ -n "$volume_name" ]; then
        echo "Remove volume : $volume_name"
        docker volume rm "$volume_name"
    fi
done < "volumes_to_remove.txt"
Enter fullscreen mode Exit fullscreen mode

Don't forget to chmod +x script.sh and :

./script.sh
Enter fullscreen mode Exit fullscreen mode

Top comments (0)