在使用私有镜像时,需要创建一个docker registry secret,并在容器中引用.如何让k8s能够拉取私有仓库的镜像

  1. 登录docker镜像仓库 这里以阿里云docker镜像仓库为例

[root@k8s-master yaml]# docker login --username=xxx@aliyun.com registry.cn-hangzhou.aliyuncs.com

之后输入密码就可以了, 这个时候我们可以在配置文件中查看登录情况 [root@k8s-master yaml]# cat ~/.docker/config.json

这个时候我们虽然可以通过docker pull命令拉取镜像, 但无法通过k8s创建pod方式拉取

  1. 生成密钥secret
[root@k8s-master yaml]# kubectl create secret -h #查看创建secret帮助
kubectl create secret docker-registry regsecret --docker-server=registry.cn-hangzhou.aliyuncs.com --docker-username=xxx@aliyucom --docker-password=xxxxxx --docker-email=xx@aliyun.com

其中: regsecret: 指定密钥的键名称, 可自行定义 --docker-server: 指定docker仓库地址 --docker-username: 指定docker仓库账号 --docker-password: 指定docker仓库密码 --docker-email: 指定邮件地址(选填)

[root@k8s-master yaml]# kubectl get secret

可以看到当前除了默认的密钥, 还有我们刚才生成的. 另外要注意的是, 该密钥只能在对应namespace使用, 也就是这里的default, 如果需要用到其他namespace, 比如说test, 就需要在生成的时候指定参数 -n test

3. yml文件加入密钥参数

containers:
- name: flannel
  image: registry-internal.cn-hangzhou.aliyuncs.com/yin32167/flannel:0.10
ports:
- containerPort: 80
imagePullSecrets:
- name: regsecret

其中imagePullSecrets是声明拉取镜像时需要指定密钥, regsecret 必须和上面生成密钥的键名一致, 另外检查一下pod和密钥是否在同一个namespace, 之后k8s便可以拉取镜像

k8s官方参考:https://kubernetes.io/docs/concepts/containers/images/#using-a-private-registry