当前位置: 首页 > 工具软件 > Crane > 使用案例 >

go-containerregistry 将crane 保存的tar导入docker daemon 中

孙才捷
2023-12-01

先将镜像从远程仓库拉取保存至指定tar,然后load并导入docker daemon

package main

import (
	"flag"
	"fmt"
	"github.com/google/go-containerregistry/pkg/crane"
	"github.com/google/go-containerregistry/pkg/name"
	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/daemon"
	"os"
)

func main() {
	var (
		srcName string
		dstName string
	)
	flag.StringVar(&srcName, "src", "", "镜像名")
	flag.StringVar(&dstName, "dst", "", "镜像名")
	flag.Parse()
	DownloadImage(srcName, dstName)
}

func DownloadImage(srcName, dstName string) {
	var (
		image v1.Image
		err   error
	)

	//1. Pull image from remote warehouse
	image, err = crane.Pull(srcName)
	if err != nil {
		fmt.Println("crane.Pull function failed, err :", err.Error())
		return
	}

	//2. Gets the hash value of the image
	m, err := image.Manifest()
	imageFullHash := m.Config.Digest.Hex
	fmt.Println("image hash:", imageFullHash)

	//3. Create mirrored storage path
	Imagestoragedir := "tmp" // the default value is TMP directory
	err = os.MkdirAll(Imagestoragedir, 0755)
	if err != nil {
		fmt.Printf("mkdir %s failed!\n")
		return
	}
	imagePath := Imagestoragedir + "/package.tar"

	err = crane.Save(image, "./data", imagePath)
	if err != nil {
		fmt.Println("crane.Save function failed")
		return
	}

	img2, err := crane.Load(imagePath)
	if err != nil {
		fmt.Println(" crane.Load function failed err:", err.Error())
		return
	}
	tag3, _ := name.NewTag(dstName)

	str, err := daemon.Write(tag3, img2)
	if err != nil {
		fmt.Println("daemon.Write function failed")
		return
	} else {
		fmt.Println(str)
	}

}

运行结果如下:

# ./crane  -src 192.168.x.x:80/library/goharbor/registry-photon:v2.4.2  -dst registry-photon:test
image hash: 62aedd01bd8520c43d06b09f7a0f67ba9720bdc04631a8242c65ea995f3ecac8
{"stream":"Loaded image: registry-photon:test\n"}

 类似资料: