Skip to content

Instantly share code, notes, and snippets.

@surrbsk10
Last active July 17, 2020 08:34
Show Gist options
  • Save surrbsk10/b757d1a73574413063e4087d43a2fef8 to your computer and use it in GitHub Desktop.
Save surrbsk10/b757d1a73574413063e4087d43a2fef8 to your computer and use it in GitHub Desktop.
Python Class to clean exited docker containers and untagged docker images in the native docker env. To Install python docker package : pip install docker
"""
Python Class to clean exited docker containers and untagged docker images in the native env
Actions are performed used by Docker - Python SDK
__author__ = "Suresh Kumar B"
__email__ = "sureshsurya1096@gmail.com"
"""
import docker, docker.errors
class DockerCleaner:
def __init__(self):
self._client = docker.from_env()
self._version = self._client.version()
self._config = self._client.configs
def _get_all_images(self):
try:
return self._client.images.list()
except docker.errors.APIError:
return None
def _delete_container(self, container_id):
try:
if self._client.containers.get(container_id) is not None:
self._client.api.remove_container(container_id)
return "deleted"
except docker.errors.APIError as exc:
print(exc)
return None
def remove_stopped_containers(self):
try:
for container in self._client.containers.list(all=True):
container_state = container.attrs['State']
(container_status, running_status) = (container_state['Status'], container_state['Running'])
if (container_status, running_status) != ('running', True):
self._delete_container(container.id)
return "Deleted dead containers"
except docker.errors.APIError:
print(f"Error occurred at cleaning containers")
return None
def remove_untagged_images(self):
try:
for image in self._get_all_images():
if (not image.attrs['RepoTags']) and (not image.attrs['RepoDigests']) and (not image.tags):
self._client.api.remove_image(image.id)
return "Deleted Untagged Images"
except docker.errors.APIError as exc:
print(exc)
return None
docker_cleaner_client = DockerCleaner()
container_removal_status = docker_cleaner_client.remove_stopped_containers()
if container_removal_status is not None:
print(f"Stale Containers have been removed successfully!")
images_removal_status = docker_cleaner_client.remove_untagged_images()
if images_removal_status is not None:
print(f"Untagged Images have been removed successfully!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment