Skip to content

Instantly share code, notes, and snippets.

@eliasp
Created November 30, 2013 16:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eliasp/7720943 to your computer and use it in GitHub Desktop.
Save eliasp/7720943 to your computer and use it in GitHub Desktop.
A short python script to remove orphaned Docker volumes
#!/usr/bin/python
import json
import os
import shutil
import subprocess
import re
dockerdir = '/var/lib/docker'
volumesdir = os.path.join(dockerdir, 'volumes')
containers = dict((line, 1) for line in subprocess.check_output('docker ps -a -q -notrunc', shell=True).splitlines())
volumes = os.walk(os.path.join(volumesdir, '.')).next()[1]
for volume in volumes:
if not re.match('[0-9a-f]{64}', volume):
print volume + ' is not a valid volume identifier, skipping...'
continue
volume_metadata = json.load(open(os.path.join(volumesdir, volume, 'json')))
container_id = volume_metadata['container']
if container_id in containers:
print 'Container ' + container_id[:12] + ' does still exist, not clearing up volume ' + volume
continue
print 'Deleting volume ' + volume + ' (container: ' + container_id[:12] + ')'
volumepath = os.path.join(volumesdir, volume)
print 'Volumepath: ' + volumepath
shutil.rmtree(volumepath)
@yorch
Copy link

yorch commented Aug 4, 2014

Thanks for the script! Just made two minor changes when using newer docker version (currently 1.1.2):
https://gist.github.com/yorch/39c96308e00fd21eaa94

@emagma
Copy link

emagma commented Nov 21, 2014

Hi there, useful script, I also made a couple of fixes for docker 1.3
https://gist.github.com/emagma/f3de4ed66e65012fdac1

@hxu
Copy link

hxu commented Dec 4, 2014

It seems like this doesn't clean the /var/lib/docker/vfs/dir folders. Do those also need to be removed in order to fully remove a volume?

@cloudnautique
Copy link

@hxu, as this script is written, I found it only cleans out the metadata and not the data. I used this script as the basis for https://github.com/cloudnautique/docker-volume-cleanup I'd be interested in feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment