Last active
August 29, 2015 14:09
-
-
Save renfredxh/88341f9f2ec1c7329251 to your computer and use it in GitHub Desktop.
Clean untagged Docker images and zombie containers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Description: Sometimes after building, starting and killing a number of | |
# docker containers over time, you end up with images that cannot be removed | |
# removed because zombie containers are referencing them. This removes all | |
# images of a given name or untagged images and the container that | |
# reference them. | |
# | |
# Disclaimer: This is recommended for development environments only. | |
# Frivolous usage may result in unintended data loss. | |
# | |
# Usage: clean-images image_name | |
# Name of the image to remove. Default is all untagged (labeled <none>) images. | |
image_name = ARGV[0] || "<none>" | |
begin | |
# Attempt to remove all images of the specified name. | |
output = `sudo docker rmi $(sudo docker images | grep "#{image_name} " | awk '{print($3)}') 2>&1` | |
puts output | |
# Find images that could not be removed because a container references them. | |
containers = output.scan(/Conflict, cannot delete [a-f0-9]+ because the container ([a-f0-9]+) is using it/) | |
# Remove each of these containers and repeat until all untagged images are gone. | |
containers.each do |container| | |
puts "Removing #{container[0]}" | |
puts `sudo docker rm #{container[0]}` | |
end | |
end while containers.length > 0 | |
puts "Finished" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment