且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Docker中获取依赖子映像的列表?

更新时间:2023-11-24 20:08:40

简短答案: 这是一个python3脚本,其中列出了相关的docker映像.

Short answer: Here is a python3 script that lists dependent docker images.

长答案: 您可以使用以下内容查看在有问题的图像之后创建的所有图像的图像ID和父ID:

Long answer: You can see the image id and parent id for all image created after the image in question with the following:

docker inspect --format='{{.Id}} {{.Parent}}' \
    $(docker images --filter since=f50f9524513f --quiet)

您应该能够查找以f50f9524513f开头的父ID的图像,然后查找那些的子图像,等等.但是 .Parent 并不是您所想的.,因此在大多数情况下,您需要在上面指定docker images --all才能使该功能生效,然后您将还要获取所有中间层的图像ID.

You should be able to look for images with parent id starting with f50f9524513f, then look for child images of those, etc.. But .Parent isn’t what you think., so in most cases you would need to specify docker images --all above to make that work, then you will get image ids for all intermediate layers as well.

这是一个更加有限的python3脚本,用于解析docker输出并进行搜索以生成图像列表:

Here's a more limited python3 script to parse the docker output and do the searching to generate the list of images:

#!/usr/bin/python3
import sys

def desc(image_ids, links):
    if links:
        link, *tail = links
        if len(link) > 1:
            image_id, parent_id = link
            checkid = lambda i: parent_id.startswith(i)
            if any(map(checkid, image_ids)):
                return desc(image_ids | {image_id}, tail)
        return desc(image_ids, tail)
    return image_ids


def gen_links(lines):
    parseid = lambda s: s.replace('sha256:', '')
    for line in reversed(list(lines)):
        yield list(map(parseid, line.split()))


if __name__ == '__main__':
    image_ids = {sys.argv[1]}
    links = gen_links(sys.stdin.readlines())
    trunc = lambda s: s[:12]
    print('\n'.join(map(trunc, desc(image_ids, links))))

如果将其另存为desc.py,则可以按以下方式调用它:

If you save this as desc.py you could invoke it as follows:

docker images \
    | fgrep -f <(docker inspect --format='{{.Id}} {{.Parent}}' \
        $(docker images --all --quiet) \
        | python3 desc.py f50f9524513f )

或者只需使用上面的要点,即可执行相同的操作.

Or just use the gist above, which does the same thing.