golang调用docker api pull/push image到私有仓库,daemon.json增加insecure-registries

目录

pull

没有配置/etc/docker/daemon.json

配置了/etc/docker/daemon.json

完整代码

push

X-Registry-Auth

RegistryAuth值为空

RegistryAuth不为空,但是值不正确

x509: certificate signed by unknown authority

完整代码

配置daemon.json,增加私有仓库地址到insecure-registry

通过不重启docker的方式修改daemon.json




pull

没有配置/etc/docker/daemon.json

报错

Error response from daemon: Get https://reg.test.ocp.c2g.cn/v2/: x509: certificate signed by unknown authority

配置了/etc/docker/daemon.json

pull 正常,不需要私有仓库的账号密码

完整代码

package main

import (
	"bytes"
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"io"
)

func main()  {
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err.Error())
	}
	fmt.Println(cli.ClientVersion())
	fmt.Println("=====pull image=====")
	image := "xx/root/xx.cn:node-bootstrap-go-master"
	var pullReader io.ReadCloser
	pullReader, err = cli.ImagePull(context.Background(), image, types.ImagePullOptions{
		All:           false,
		RegistryAuth:  "",
		PrivilegeFunc: nil,
	})
	if err != nil {
		panic(err.Error())
	}
	defer pullReader.Close()
	buf := new(bytes.Buffer)
	buf.ReadFrom(pullReader)
	s := buf.String()
	fmt.Println("info:", s)
	fmt.Println("image pull success")
}

push

X-Registry-Auth

	var pushReader io.ReadCloser
	pushReader, err  = cli.ImagePush(context.Background(), image, types.ImagePushOptions{
		All:           false,
		RegistryAuth:  "",
		PrivilegeFunc: nil,
	})

RegistryAuth值为空

如果RegistryAuth没有值,那么会报错

panic: Error response from daemon: Bad parameters and missing X-Registry-Auth: EOF

https://github.com/moby/moby/issues/10983

RegistryAuth不为空,但是值不正确

那么会报错

"errorDetail":{"message":"unauthorized: access to the requested resource is not authorized"},"error":"unauthorized: access to the requested resource is not authorized"}

x509: certificate signed by unknown authority

需要配置/etc/docker/daemon.json

在/etc/docker/daemon.json 添加--insecure-registry把私有镜像仓库放进去,比如

// reg.test.ocp.c2g.cn 是私有仓库地址
[root@infra docker-demo]# vim /etc/docker/daemon.json 
 
{
  "registry-mirrors": ["https://xx.aliyuncs.com"],
  "insecure-registries": ["reg.test.ocp.c2g.cn"]
}

完整代码

package main

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"io"
)

func main()  {
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err.Error())
	}
	fmt.Println(cli.ClientVersion())
	image := "xx/root/xx.cn:monitoring-1.0.0"
	user := "root"
	password := "11111111"
	authConfig := types.AuthConfig{Username: user, Password: password}
	encodedJSON, err := json.Marshal(authConfig)
	if err != nil {
		panic(err)
	}
	authStr := base64.URLEncoding.EncodeToString(encodedJSON)
	fmt.Println("push image")
	var pushReader io.ReadCloser
	pushReader, err  = cli.ImagePush(context.Background(), image, types.ImagePushOptions{
		All:           false,
		RegistryAuth:  authStr,
		PrivilegeFunc: nil,
	})
	if err != nil {
		panic(err.Error())
	}
	defer pushReader.Close()
	buf1 := new(bytes.Buffer)
	buf1.ReadFrom(pushReader)
	s1 := buf1.String()
	fmt.Println("info:", s1)
	fmt.Println("image push success")
}

配置daemon.json,增加私有仓库地址到insecure-registry

代码方式动态配置/etc/docker/daemon.json

daemon.json默认内容如下,(是默认给的内容)

{
     "registry-mirrors": [
          "http://mirror.local"
     ],
     "insecure-registries": [
          "registry.local"
     ],
     "mtu": 1360,
     "bip": "192.168.1.1/24"
}

现在新增的私有仓库地址为:xxx.xxx.xxx.xx

golang动态添加insecure-registry

完整代码

package main

import (
	jsoniter "github.com/json-iterator/go"
	"io/ioutil"
	"os"
)

type DaemonJson struct {
	RegistryMirrors    []string `json:"registry-mirrors"`
	InsecureRegistries []string `json:"insecure-registries"`
	Mtu                float64  `json:"mtu"`
	Bip                string   `json:"bip"`
}

func main() {
	pwd, _ := os.Getwd()
	filePath := pwd + string(os.PathSeparator) + "/etc/daemon.json"
	body, err := ioutil.ReadFile(filePath)
	if err != nil {
		panic(err.Error())
	}
	var daemon DaemonJson
	err = jsoniter.Unmarshal(body, &daemon)
	if err != nil {
		panic(err.Error())
	}
	registry := "xxx.xxx.xxx.xxx"
	daemon.InsecureRegistries = append(daemon.InsecureRegistries, registry)
    // MarshalIndent,增加缩进,格式化输出daemon.json
	content, err1 := jsoniter.MarshalIndent(daemon, "", "     ")
	if err1 != nil {
		panic(err1.Error())
	}
	err = ioutil.WriteFile(filePath, content, 0600)
	if err != nil {
		panic(err.Error())
	}
}

最终实现的效果

{
     "registry-mirrors": [
          "http://mirror.local"
     ],
     "insecure-registries": [
          "registry.local",
          "xxx"
     ],
     "mtu": 1360,
     "bip": "192.168.1.1/24"
}

修改了daemon.json后需要重启docker才会生效

systemctl restart docker

通过不重启docker的方式修改daemon.json

dockerd启动的时候读取的是/etc/docker/daemon.json,要想不用重启docker,那么可以在dockerd启动之前把daemon.json里面的内容替换掉。

在dockerd的启动脚本/usr/local/bin/dockerd-entrypoint.sh前替换想要修改的内容

脚本内容为把daemon.json中的registry.local字符串替换为环境变量IMAGE_REGISTRY的值。

#!/usr/bin/env bash
export LANG=zh_CN.utf8
sed -i "s/registry.local/$IMAGE_REGISTRY/g" /etc/docker/daemon.json
/usr/local/bin/dockerd-entrypoint.sh &

猜你喜欢

转载自blog.csdn.net/u010918487/article/details/105788735