Skip to content

Instantly share code, notes, and snippets.

@Lakret
Last active August 29, 2020 13:15
Show Gist options
  • Save Lakret/c7031e25fe838ec0980d35885cdc8f7b to your computer and use it in GitHub Desktop.
Save Lakret/c7031e25fe838ec0980d35885cdc8f7b to your computer and use it in GitHub Desktop.
Docker images cleanup
## This script removes all docker images with name `<none>`.
## Typically, this frees a lot of disk space if you often use different docker images.
## Removal is forced, i.e. `docker rmi -f` is used.
{output, 0} = System.cmd("docker", ["images"])
images =
output |> String.split("\n") |> Enum.drop(1) |> Enum.map(fn line ->
# since docker output is aligned by spaces, we need to do this trick here:
# we know that valid records in any column will not have repeated spaces,
# so all repeated spaces are part of a column separator
case String.split(line, " ", trim: true) do
[name, tag, id, date, size] ->
image = %{name: name, tag: tag, id: id, date: date, size: size}
# we still can have some values prefixed or postfixed by spaces
# in case of odd number of spaces in a column separator
Enum.map(image, fn {k, v} -> {k, String.trim(v)} end) |> Enum.into(%{})
unknown ->
IO.inspect(unknown, label: :unknown)
nil
end
end) |> Enum.reject(&is_nil/1)
images_to_delete = Enum.filter(images, fn image -> image.name == "<none>" end)
images_removed =
for image <- images_to_delete do
case System.cmd("docker", ["rmi", "-f", image.id]) do
{_output, 0} ->
IO.puts("deleted #{image.id}, freed #{image.size}.")
1
{output, exit_code} ->
IO.puts("failed to delete #{image.id}, exit code: #{exit_code}, output: #{output}.")
0
end
end |> Enum.sum()
IO.puts("removed #{images_removed} images.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment