如何在不删除任何图层的情况下删除Docker映像上的标签

时间:2019-12-06 04:15:09

标签: docker

我可以使用Array.Sort(books, (x, y) => string.Compare(x.GStitle, y.GStitle, StringComparison.InvariantCulture)); 保留最多的个图层;但是我发现它删除了最后一层。

一个简化的示例:

Dockerfile:

public static void Main()
{
    var books = new Book[]
    {
        new Book() {GStitle = "E"},
        new Book() {GStitle = "D"},
        new Book() {GStitle = "C"},
        new Book() {GStitle = "B"},
        new Book() {GStitle = "A"}
    };

    Console.WriteLine("Before sort.");
    foreach (var book in books)
    {
        Console.WriteLine(book.GStitle);
    }

    Array.Sort(books, (x, y) => string.Compare(x.GStitle, y.GStitle, StringComparison.InvariantCulture));
    //BookSort(books);

    Console.WriteLine("After sort.");
    foreach (var book in books)
    {
        Console.WriteLine(book.GStitle);
    }
}

public class Book
{
    public string GStitle { get; set; }
}

public static void BookSort(Book[] books)
{
    for (int y = 0; y < books.Length; y++)
    {
        for (int x = 0; x < books.Length - 1 - y; x++)
        {
            if (string.Compare(books[x].GStitle, books[x + 1].GStitle, StringComparison.InvariantCulture) > 0)
            {
                var temp = books[x];
                books[x] = books[x + 1];
                books[x + 1] = temp;
            }
        }
    }
}

构建它:

docker image rm --no-prune my:image

然后再次构建它:

FROM alpine
RUN echo "hello"
RUN echo "world"

请注意,步骤已缓存。现在,如果我使用$ docker build --tag my:image . Sending build context to Docker daemon 2.048kB Step 1/3 : FROM alpine latest: Pulling from library/alpine 89d9c30c1d48: Pull complete Digest: sha256:c19173c5ada610a5989151111163d28a67368362762534d8a8121ce95cf2bd5a Status: Downloaded newer image for alpine:latest ---> 965ea09ff2eb Step 2/3 : RUN echo "hello" ---> Running in dff99f3e8991 hello Removing intermediate container dff99f3e8991 ---> bffa49d7d012 Step 3/3 : RUN echo "world" ---> Running in 20101e7149ba world Removing intermediate container 20101e7149ba ---> 9f6a7f60fd0d Successfully built 9f6a7f60fd0d Successfully tagged my:image 删除图像,则cli报告它已删除了SHA:

$ docker build --tag my:image .                                                                                                                    [16:59:58]
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM alpine
 ---> 965ea09ff2eb
Step 2/3 : RUN echo "hello"
 ---> Using cache
 ---> bffa49d7d012
Step 3/3 : RUN echo "world"
 ---> Using cache
 ---> 9f6a7f60fd0d
Successfully built 9f6a7f60fd0d
Successfully tagged my:image

现在,当我重建图像时,最后一层将被重建:

--no-prune

如何防止docker在从图像中删除标签的同时删除最后一层?

1 个答案:

答案 0 :(得分:0)

因此,我放弃了尝试为此寻找一个好的解决方案的方法。并使用了hacky版本。

通过使用其他标签标记图像,删除图像不会删除任何图层。然后,将该标签移动到另一张图像仍不会删除图像层。因此,要保留所有图层,请执行以下操作:

docker image tag my:image tmp
docker image rm my:image

显然,这会留下tmp图像,因此我们可以用类似的方式将其删除(其中alpine是您要保留的图像):

docker image tag alpine tmp
docker image rm tmp

无需使用--no-prune,因为如果有其他引用,则docker不会删除这些层。