【docker API】docker client go 之image接口
1 docker client 创建func NewClient(server, port, version string) (*client.Client, error) {host := "tcp://" + server + ":" + portreturn client.NewClient(host, version, nil, map[string
·
1 docker client 创建
func NewClient(server, port, version string) (*client.Client, error) {
host := "tcp://" + server + ":" + port
return client.NewClient(host, version, nil, map[string]string{"Content-type": "application/x-tar"})
}
2 docker build image
根据ImageBuild接口,生成的镜像名为ImageBuildOptions,比较鸡贼,一直在找哪个是repo名字,内心崩溃
设置Labels好处是ListImage可以根据这个过滤参照https://docs.docker.com/engine/api/v1.37/#operation/ImageList
func BuildImage(cli *client.Client, tarFile, project, imageName string) error {
dockerBuildContext, err := os.Open(tarFile)
if err != nil {
return err
}
defer dockerBuildContext.Close()
buildOptions := types.ImageBuildOptions{
Dockerfile: "Dockerfile", // optional, is the default
Tags: []string{imageName},
Labels: map[string]string{
project: "project",
},
}
output, err := cli.ImageBuild(context.Background(), dockerBuildContext, buildOptions)
if err != nil {
return err
}
body, err := ioutil.ReadAll(output.Body)
if err != nil {
return err
}
dlog.Infof("Build resource image output: %v", string(body))
if strings.Contains(string(body), "error") {
return fmt.Errorf("build image to docker error")
}
return nil
}
3 docker push image
对于docker 需要认证,直接调用ImagePush没什么好说的了
func PushImage(cli *client.Client, registryUser, registryPassword, image string) error {
authConfig := types.AuthConfig{
Username: registryUser,
Password: registryPassword,
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
return err
}
dlog.Infof("Push docker image registry: %v %v", registryUser, registryPassword)
authStr := base64.URLEncoding.EncodeToString(encodedJSON)
out, err := cli.ImagePush(context.TODO(), image, types.ImagePushOptions{RegistryAuth: authStr})
if err != nil {
return err
}
body, err := ioutil.ReadAll(out)
if err != nil {
return err
}
dlog.Infof("Push docker image output: %v", string(body))
if strings.Contains(string(body), "error") {
return fmt.Errorf("push image to docker error")
}
return nil
}
其他接口雷同,一看既会
参考
https://docs.docker.com/engine/api/v1.37/#operation/ImageCreate
更多推荐
已为社区贡献14条内容
所有评论(0)