Golang Docker SDK ImagePull 下载镜像成功但镜像列表中却不存在
Golang Docker SDK ImagePull 下载镜像成功但镜像列表中却不存在
在使用 Golang Docker SDK 开发过程中,你可能会遇到使用 ImagePull 方法下载镜像显示成功,打印出来的日志也是成功的,但是使用 docker images 命令行和 docker sdk 中的 ImageList 方法输出的结果却没有这个镜像。然而,通过 docker pull 命令拉取镜像是存在的。
问题原因
出现这种情况的原因是 ImageList 方法默认只返回本地镜像,而不包括从远程仓库拉取的镜像。当你使用 ImagePull 方法下载镜像时,镜像会被下载到本地,但并不会被标记为本地镜像,因此 ImageList 方法无法找到它。
解决方案
要解决这个问题,你可以使用 ImageList 方法的 WithFilters 选项来获取远程仓库的镜像。WithFilters 选项允许你根据特定条件过滤镜像列表,包括镜像标签、仓库等。
以下代码演示了如何使用 WithFilters 选项获取所有镜像(包括本地和远程仓库的):goimport ( 'context' 'fmt'
'github.com/docker/docker/api/types' 'github.com/docker/docker/client')
func main() { ctx := context.Background() cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { panic(err) }
// 使用 WithFilter 选项获取所有镜像 images, err := cli.ImageList(ctx, types.ImageListOptions{All: true}) if err != nil { panic(err) }
for _, image := range images { fmt.Println(image.ID) }}
注意: 将 ImageListOptions 中的 All 设置为 true 可以获取所有镜像,包括中间层镜像。
通过使用 WithFilters 选项,你可以根据需要灵活地获取镜像列表,避免因为默认设置而导致获取不到所需镜像的问题。
原文地址: http://www.cveoy.top/t/topic/fPnf 著作权归作者所有。请勿转载和采集!