k8s的imagePullSecrets如何生成及使用

本文详细介绍如何在Kubernetes中使用私有Docker仓库(harbor),包括通过Secret处理敏感信息,生成和使用secret,以及在deployment yaml文件中的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、概述

http://docs.kubernetes.org.cn/548.html

https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/

https://blog.csdn.net/u010278923/article/details/72857928

公司的docker仓库(harbor),是私有的,需要用户认证之后,才能拉取镜像。

Secret

Kubernetes提供了Secret来处理敏感信息,目前Secret的类型有3种:
Opaque(default): 任意字符串
kubernetes.io/service-account-token: 作用于ServiceAccount,就是上面说的。
kubernetes.io/dockercfg: 作用于Docker registry,用户下载docker镜像认证使用。

 

二、生成secret

登录docker

登录到k8s master节点,先登录docker

root@k8s-master:~# docker login 192.168.10.122 -u admin -p Harbor12345
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://192.168.10.122/v2/: dial tcp 192.168.10.122:443: connect: connection refused

注意:出现这个报错,是由于harbor为了安全性考虑,默认是需要https证书支持的

但是我们可以通过一个简单的办法解决

修改 /etc/docker/daemon.json 文件

vim /etc/docker/daemon.json

内容如下:

{"insecure-registries": ["192.168.10.122"]}

重新加载docker配置

/etc/init.d/docker reload

再次登录

root@k8s-master:~# docker login 192.168.10.122 -u admin -p Harbor12345
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

提示登录成功。

 

登录过程创建或更新一个包含授权令牌的config.json文件。
查看config.json文件:

cat ~/.docker/config.json
{
    "auths": {
        "192.168.10.122": {
            "auth": "YWRtaW46SGFyYm9yMTIzNDU="
        }
    },
    "HttpHeaders": {
        "User-Agent": "Docker-Client/19.03.1 (linux)"
    }
}
复制代码

注意:如果您使用Docker凭据存储,您将看不到该auth条目,而是看到一个以存储名称为值的credsstore条目

基于现有Docker凭据创建secret

kubernetes集群使用docker注册表类型的秘密对容器注册表进行身份验证,以获取私有映像。

如果您已经运行了Docker登录,则可以将该凭证复制到Kubernetes中:

 

kubectl create secret generic harborsecret \
    --from-file=.dockerconfigjson=/root/.docker/config.json \
    --type=kubernetes.io/dockerconfigjson
或
kubectl create secret generic harborsecret \
    --from-file=/root/.docker/config.json \
    --type=kubernetes.io/dockerconfigjson

或者

kubectl create secret docker-registry harborsecret --docker-server=<your-registry-server> --docker-username=<your-name> --docker-password=<your-pword> --docker-email=<your-email>

注意:主要修改红色部分。

apiVersion: v1
data:
  .dockerconfigjson: ewoJImF1dGhzIjogewoJCSIxOTIuMTY4LjEwLjEyMiI6IHsKCQkJImF1dGgiOiAiWVdSdGFXNDZTR0Z5WW05eU1USXpORFU9IgoJCX0KCX0sCgkiSHR0cEhlYWRlcnMiOiB7CgkJIlVzZXItQWdlbnQiOiAiRG9ja2VyLUNsaWVudC8xOS4wMy4xIChsaW51eCkiCgl9Cn0=
kind: Secret
metadata:
  creationTimestamp: "2019-08-30T06:14:10Z"
  name: harborsecret
  namespace: default
  resourceVersion: "6128"
  selfLink: /api/v1/namespaces/default/secrets/harborsecret
  uid: 76e16e61-a6b9-4a47-a842-e884cf6f468d
type: kubernetes.io/dockerconfigjson

harborsecret 表示key名

/root/.docker/config.json 表示docker认证文件,注意要写绝对路径。

查看内容

kubectl get secrets harborsecret --output="jsonpath={.data.\.dockerconfigjson}" | base64 -d
{
    "auths": {
        "192.168.10.122": {
            "auth": "YWRtaW46SGFyYm9yMTIzNDU="
        }
    },
    "HttpHeaders": {
        "User-Agent": "Docker-Client/19.03.1 (linux)"
    }
}

要了解刚刚创建的regcred秘密的内容,请从以yaml格式查看秘密开始:

kubectl get secret harborsecret --output=yaml

 

三、在demployment yaml文件中的使用示例

... 
spec:
      imagePullSecrets:
      - name:harborsecret
      containers:
      - name: eureka
        image: 192.168.10.122/library/alpine:latest
...

 

如果需要删除secret,使用命令

kubectl delete secrets harborsecret

 

=====================================================================

Pull an Image from a Private Registry

This page shows how to create a Pod that uses a Secret to pull an image from a private Docker registry or repository.

Before you begin

  •  

    You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using Minikube, or you can use one of these Kubernetes playgrounds:

    To check the version, enter kubectl version.

     

  • To do this exercise, you need a Docker ID and password.

Log in to Docker

On your laptop, you must authenticate with a registry in order to pull a private image:

docker login

When prompted, enter your Docker username and password.

The login process creates or updates a config.json file that holds an authorization token.

View the config.json file:

cat ~/.docker/config.json

The output contains a section similar to this:

{
    "auths": {
        "https://index.docker.io/v1/": {
            "auth": "c3R...zE2"
        }
    }
}

Note: If you use a Docker credentials store, you won't see that auth entry but a credsStore entry with the name of the store as value.

Create a Secret based on existing Docker credentials

A Kubernetes cluster uses the Secret of docker-registry type to authenticate with a container registry to pull a private image.

If you already ran docker login, you can copy that credential into Kubernetes:

kubectl create secret generic regcred \
    --from-file=.dockerconfigjson=<path/to/.docker/config.json> \
    --type=kubernetes.io/dockerconfigjson

If you need more control (for example, to set a namespace or a label on the new secret) then you can customise the Secret before storing it. Be sure to:

  • set the name of the data item to .dockerconfigjson
  • base64 encode the docker file and paste that string, unbroken as the value for field data[".dockerconfigjson"]
  • set type to kubernetes.io/dockerconfigjson

Example:

apiVersion: v1
kind: Secret
metadata:
  name: myregistrykey
  namespace: awesomeapps
data:
  .dockerconfigjson: UmVhbGx5IHJlYWxseSByZWVlZWVlZWVlZWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGx5eXl5eXl5eXl5eXl5eXl5eXl5eSBsbGxsbGxsbGxsbGxsbG9vb29vb29vb29vb29vb29vb29vb29vb29vb25ubm5ubm5ubm5ubm5ubm5ubm5ubm5ubmdnZ2dnZ2dnZ2dnZ2dnZ2dnZ2cgYXV0aCBrZXlzCg==
type: kubernetes.io/dockerconfigjson

If you get the error message error: no objects passed to create, it may mean the base64 encoded string is invalid. If you get an error message like Secret "myregistrykey" is invalid: data[.dockerconfigjson]: invalid value ..., it means the base64 encoded string in the data was successfully decoded, but could not be parsed as a .docker/config.json file.

Create a Secret by providing credentials on the command line

Create this Secret, naming it regcred:

kubectl create secret docker-registry regcred --docker-server=<your-registry-server> --docker-username=<your-name> --docker-password=<your-pword> --docker-email=<your-email>

where:

  • <your-registry-server> is your Private Docker Registry FQDN. (https://index.docker.io/v1/ for DockerHub)
  • <your-name> is your Docker username.
  • <your-pword> is your Docker password.
  • <your-email> is your Docker email.

You have successfully set your Docker credentials in the cluster as a Secret called regcred.

Note: Typing secrets on the command line may store them in your shell history unprotected, and those secrets might also be visible to other users on your PC during the time that kubectl is running.

Inspecting the Secret regcred

To understand the contents of the regcred Secret you just created, start by viewing the Secret in YAML format:

kubectl get secret regcred --output=yaml

The output is similar to this:

apiVersion: v1
kind: Secret
metadata:
  ...
  name: regcred
  ...
data:
  .dockerconfigjson: eyJodHRwczovL2luZGV4L ... J0QUl6RTIifX0=
type: kubernetes.io/dockerconfigjson

The value of the .dockerconfigjson field is a base64 representation of your Docker credentials.

To understand what is in the .dockerconfigjson field, convert the secret data to a readable format:

kubectl get secret regcred --output="jsonpath={.data.\.dockerconfigjson}" | base64 --decode

The output is similar to this:

{"auths":{"your.private.registry.example.com":{"username":"janedoe","password":"xxxxxxxxxxx","email":"jdoe@example.com","auth":"c3R...zE2"}}}

To understand what is in the auth field, convert the base64-encoded data to a readable format:

echo "c3R...zE2" | base64 --decode

The output, username and password concatenated with a :, is similar to this:

janedoe:xxxxxxxxxxx

Notice that the Secret data contains the authorization token similar to your local ~/.docker/config.json file.

You have successfully set your Docker credentials as a Secret called regcred in the cluster.

Create a Pod that uses your Secret

Here is a configuration file for a Pod that needs access to your Docker credentials in regcred:

pods/private-reg-pod.yaml 

apiVersion: v1
kind: Pod
metadata:
  name: private-reg
spec:
  containers:
  - name: private-reg-container
    image: <your-private-image>
  imagePullSecrets:
  - name: regcred

Download the above file:

wget -O my-private-reg-pod.yaml https://k8s.io/examples/pods/private-reg-pod.yaml

In file my-private-reg-pod.yaml, replace <your-private-image> with the path to an image in a private registry such as:

your.private.registry.example.com/janedoe/jdoe-private:v1

To pull the image from the private registry, Kubernetes needs credentials. The imagePullSecrets field in the configuration file specifies that Kubernetes should get the credentials from a Secret named regcred.

Create a Pod that uses your Secret, and verify that the Pod is running:

kubectl apply -f my-private-reg-pod.yaml
kubectl get pod private-reg

What's next

Feedback

### Kubernetes 中集成和使用 Harbor 镜像仓库 #### 安装 Harbor 为了使 Kubernetes 能够利用 Harbor 作为私有镜像库,首先需要确保 Harbor 已经被正确安装并运行在一个拥有 Docker 支持的环境中或者直接部署于 Kubernetes 环境下[^1]。对于希望实现更高可用性的场景,则需考虑采用带有共享存储机制(例如 CephFS)的设计来构建 HA 架构下的 Harbor 实例[^2]。 #### 准备工作 在准备阶段,应确认已获取到用于访问 Harbor 的凭证信息以及必要的 CA 证书文件路径。如果打算让 K8S Pod 自动拉取来自 Harbor 的镜像而无需额外认证操作的话,还需要提前完成相关配置项设置,比如通过修改 kubelet 启动参数等方式指定不验证服务器端 TLS 或者提供自定义 CA 文件位置等措施解决可能存在的 SSL/TLS 认证失败问题[^3]。 #### 创建 Secret 对象 为了让 Pods 可以顺利地从 Harbor 下载所需镜像,在大多数情况下都需要创建一个名为 `docker-registry` 类型的秘密对象 (Secret),其中包含了登录 Harbor 所必需的身份验证数据: ```yaml apiVersion: v1 kind: Secret metadata: name: my-harbor-secret type: kubernetes.io/dockerconfigjson data: .dockercfg: <base64-encoded-auth-file> ``` 上述 YAML 片段中的 `<base64-encoded-auth-file>` 应替换为经过 Base64 编码处理后的 JSON 格式的 `.docker/config.json` 文件内容,该文件通常由命令行工具 docker login 成功执行后生成,并保存着针对特定注册表的有效授权令牌。 #### 更新 Deployment/Job/Cronjob Spec 当成功建立了指向 Harbor 的秘密资源之后,下一步就是在目标应用的工作负载描述符里添加 imagePullSecret 字段引用此 Secret 名字,从而允许这些组件能够依据所提供的凭据去请求下载位于远程仓库里的定制化映射版本: ```yaml spec: template: spec: containers: - name: example-container image: harbor.example.com/library/example-image:latest imagePullSecrets: - name: my-harbor-secret ``` 以上代码片段展示了怎样更新 deployment、job 或 cronjob 的模板部分以便它们知道去哪里寻找对应的镜像及其关联的安全资料。 #### 测试连接性 最后一步是要测试整个流程是否正常运作——即尝试启动一个新的 pod 并观察它能否顺利完成初始化过程而不遇到任何关于无法找到或加载所指明镜像的问题;同时也可以借助 kubectl describe 命令查看更详细的日志记录帮助排查潜在错误原因。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值