Improve image pruning robustness

If you different images with the same git SHA, on the second deploy the
tag is moved and the first image becomes untagged. It may however still
be attached to an existing container.

To handle this:
1. Initially prune dangling images - this will remove any untagged
images that are not attached to an existing image
2. Then filter out the untagged images when deleting tagged images - any
that remain will be attached to a container.

The second issue is that `docker container ls -a --format '{{.Image}}`
will sometimes return the image id rather than a tag. This means that
the image doesn't get filtered out when we grep to remove the active
images.

To fix that we'll grep against both the image id and repo:tag.
This commit is contained in:
Donal McBreen
2023-05-31 09:43:50 +01:00
parent de2de19434
commit 079d9538bb
4 changed files with 24 additions and 9 deletions

View File

@@ -8,10 +8,16 @@ class CommandsPruneTest < ActiveSupport::TestCase
}
end
test "images" do
test "dangling images" do
assert_equal \
"docker image ls --filter label=service=app --format '{{.Repository}}:{{.Tag}}' | grep -v -w \"$(docker container ls -a --format '{{.Image}}\\|' --filter label=service=app | tr -d '\\n')dhh/app:latest\" | while read tag; do docker rmi $tag; done",
new_command.images.join(" ")
"docker image prune --force --filter label=service=app --filter dangling=true",
new_command.dangling_images.join(" ")
end
test "tagged images" do
assert_equal \
"docker image ls --filter label=service=app --format '{{.ID}} {{.Repository}}:{{.Tag}}' | grep -v -w \"$(docker container ls -a --format '{{.Image}}\\|' --filter label=service=app | tr -d '\\n')dhh/app:latest\\|dhh/app:<none>\" | while read image tag; do docker rmi $tag; done",
new_command.tagged_images.join(" ")
end
test "containers" do