Skip to content

Instantly share code, notes, and snippets.

@transistor1
Created March 19, 2015 04:06
Show Gist options
  • Save transistor1/bea9b29a35ee103d2ffd to your computer and use it in GitHub Desktop.
Save transistor1/bea9b29a35ee103d2ffd to your computer and use it in GitHub Desktop.
This script removes orphaned folders from docker to reclaim space. I didn't write it, but I can't remember where I got it from; it was posted on one of the github issue logs for docker. I am posting it here so I don't lose it.
#!/usr/bin/env python
"""
Check all existing Docker containers for their mapped paths, and then purge any
zombie directories in docker's volumes directory which don't correspond to an
existing container.
"""
# By using execfile(this_file, dict(__file__=this_file)) you will
this_file="/home/russosv/bin/env/bin/activate_this.py"
execfile(this_file, dict(__file__=this_file))
import logging
import os
import sys
from shutil import rmtree
import docker
DOCKER_VOLUMES_DIR = "/var/lib/docker/vfs/dir"
def get_immediate_subdirectories(a_dir):
return [os.path.join(a_dir, name) for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
def main():
logging.basicConfig(level=logging.INFO)
client = docker.Client()
valid_dirs = []
for container in client.containers(all=True):
volumes = client.inspect_container(container['Id'])['Volumes']
if not volumes:
continue
for _, real_path in volumes.iteritems():
if real_path.startswith(DOCKER_VOLUMES_DIR):
valid_dirs.append(real_path)
all_dirs = get_immediate_subdirectories(DOCKER_VOLUMES_DIR)
invalid_dirs = set(all_dirs).difference(valid_dirs)
logging.info("Purging %s dangling Docker volumes out of %s total volumes found.",
len(invalid_dirs), len(all_dirs))
for invalid_dir in invalid_dirs:
logging.info("Purging directory: %s", invalid_dir)
rmtree(invalid_dir)
logging.info("All done.")
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment