Loading

k8s ConfigMap和Secret

为什么k8s需要存储配置信息的API对象

传统的方式下,当我们需要传一些配置给我们的应用,比如Oracle的IP地址,端口号,用户名密码等配置时,最容易想到的办法就是直接在打包镜像的时候写在应用配置文件里面,但是这种方式的坏处显而易见而且非常明显;

我们也可以通过在定义pod模板时,使用env字段定义配置参数,然后容器里面的应用程序就能通过环境变量来读取配置参数,但是这样的话,当配置参数发现变化,就必须修改修改yaml文件的pod模板的env字段的参数,而且还需要重启所有的pod,让容器重新加载新参数才行。

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-env
  namespace: default
spec:
  replicas: 2
  selector:
     matchLabels:
         app: nginx-env
  template:
     metadata:
       labels:
         app: nginx-env
     spec:
         containers:
         - image: nginx:1.7.9
           name: nginx-container
           env:										#定会环境变量
           - name: dbtype							#定义一个环境变量dbtype
             value: "Oracle"						#环境变量dbtype的值是Oracle
           - name: ip								#定义一个环境变量ip
             value: "192.168.44.145"				#环境变量ip的值是192.168.44.145
           - name: port								#定义一个环境变量port
             value: "1521"							#环境变量port的值1521
           - name: dbtype_1
             value: $(dbtype)						#可以通过引用的方式引用前一个环境变量的值,前提是引用的环境变量必须先存在
           - name: dbtype_2
             value: "$(dbtype)_2"					#可以通过引用的方式引用前一个环境变量的值,前提是引用的环境变量必须先存在
           ports:
           - name: http 
             containerPort: 80

为了解决配置参数存储的问题,也为了解耦应用程序与配置参数,k8s提供了两种资源的对象来专门存储配置参数,即ConfigMap和Secret,前者ConfigMap主要存储不敏感配置信息,后者Secret存储加密的敏感配置信息。

ConfigMap

kubernetes允许将配置选项分离到单独的资源对象ConfigMap中,其本质就是一个键值对key/value的映射,我们称之为条目,value既可以是简单的数值,也可以是一个完整的配置文件。

ConfigMap创建方式

ConfigMap的键名必须是合法的DNS子域,仅包含数字字母、破折号、下划线、英语圆点。

在configmap目录下准备两个配置文件,game.properties和ui.properties

game.properties:

enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30

ui.properties:

color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

基于文件创建

基于ui.properties配置文件创建ConfigMap,ConfigMap名为ui-config。

kubectl create configmap -n killer ui-config --from-file=configmap/ui.properties

查看 ui-config。

apiVersion: v1
data:
  ui.properties: |  # 以文件名为键,以文件内容为值
    color.good=purple
    color.bad=yellow
    allow.textmode=true
    how.nice.to.look=fairlyNice
kind: ConfigMap
metadata:
  creationTimestamp: "2025-08-26T07:32:56Z"
  name: ui-config
  namespace: killer
  resourceVersion: "7832812"
  uid: 72e2b536-af5c-42a8-8d3d-b7ae60dd6468

通过--from-file=key name=configmap/ui.properties可以指定键名。

以上方式创建的ConfigMap相当于只有一条数据,如果要把文件中的每个键值对都对应到ConfigMap的键值对数据,需要--from-env-file

创建game-env-file.properties文件,内容为:

enemies=aliens
lives=3
allowed="true"

以此文件创建game-config-env-file ConfigMap。

kubectl create configmap -n killer game-config-env-file --from-env-file=configmap/game-env-file.properties

查看该ConfigMap,发现有3条数据,而非以文件命为键的一条数据。

apiVersion: v1
data:
  allowed: '"true"'
  enemies: aliens
  lives: "3"
kind: ConfigMap
metadata:
  creationTimestamp: "2025-08-26T08:30:57Z"
  name: game-config-env-file
  namespace: killer
  resourceVersion: "7839496"
  uid: d1eacd77-b5df-4a7b-9501-00df33c429ab

基于目录创建

基于configmap目录创建ConfigMap,相当于用目录下的所有文件创建ConfigMap。

kubectl create configmap -n killer config --from-file=configmap/

查看 config。

apiVersion: v1
data:   # 两个文件创建两个键值对,均以文件名为键、以文件内容为值
  game.properties: |-
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30
  ui.properties: |
    color.good=purple
    color.bad=yellow
    allow.textmode=true
    how.nice.to.look=fairlyNice
kind: ConfigMap
metadata:
  creationTimestamp: "2025-08-26T07:03:37Z"
  name: config
  namespace: killer
  resourceVersion: "7829433"
  uid: e25516ed-91f6-47a8-a9ca-f7953f5e571a

基于命令行创建

创建一个包含简单字面量literal的ConfigMap,名为my-config1,需要给每个字面量输入键名。

kubectl create configmap -n killer my-config --from-literal=dbtpye=Oracle --from-literal=ip=192.168.118.129 --from-literal=port=1521

查看my-config。

apiVersion: v1
data:
  dbtpye: Oracle 
  ip: 192.168.118.129
  port: "1521"
kind: ConfigMap
metadata:
  creationTimestamp: "2025-08-26T07:46:48Z"
  name: my-config
  namespace: killer
  resourceVersion: "7834411"
  uid: 128f0225-f983-4886-83c2-12c92a582964

混合创建

可以将所有的选项全部混合使用,如:

kubectl create configmap -n killer my-config4 --from-literal=type=html --from-file=configmap/ui.properties 

查看my-config4。

apiVersion: v1
data:  # 两条数据,一条由字面量创建,一条由文件创建
  type: html
  ui.properties: |
    color.good=purple
    color.bad=yellow
    allow.textmode=true
    how.nice.to.look=fairlyNice
kind: ConfigMap
metadata:
  creationTimestamp: "2025-08-26T07:56:23Z"
  name: my-config4
  namespace: killer
  resourceVersion: "7835515"
  uid: 68ea3125-e675-412f-827d-ede8ccd68c9d

ConfigMap使用方式

环境变量

使用 envFrom 将 ConfigMap 的数据定义为容器环境变量:

可以将整个ConfigMap都作为环境变量提供给Pod,此时ConfigMap 中的键成为 Pod 中的环境变量名称;

也可以指定某个ConfigMap中的某个值作为变量值,自定义环境变量名。

以环境变量传递的key,当ConfigMap更新条目时,并不会更新容器里环境变量,这一点是环境变量的缺陷。

整个ConfigMap作为环境变量,envFrom
apiVersion: v1
kind: Pod
metadata:
  name: env-test-pod
spec:
  containers:
    - name: env-test-pod
      image: busybox
      imagePullPolicy: IfNotPresent
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - configMapRef:
          name: game-config-env-file  # 使用game-config-env-file ConfigMap,包含enemies、lives、allowed三个键
  restartPolicy: Never

获取busybox的日志,可以查看输出的环境变量

root@k8s1:~/configmap# kubectl logs -f env-test-pod -n killer
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT=tcp://10.96.0.1:443
HOSTNAME=env-test-pod
SHLVL=1
HOME=/root
lives=3  # 来自game-config-env-file ConfigMap
enemies=aliens # 来自game-config-env-file ConfigMap
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_HOST=10.96.0.1
PWD=/
allowed="true" # 来自game-config-env-file ConfigMap
指定某个ConfigMap中的某个值作为变量值,自定义环境变量名,valueFrom
apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-cm-env
  namespace: killer
spec:
  replicas: 1
  selector:
     matchLabels:
         app: nginx-cm-env
  template:
     metadata:
       labels:
         app: nginx-cm-env
     spec:
         containers:
         - image: nginx:1.29-alpine-slim
           name: nginx-container
           env:
           - name: DBTYPE										#环境变量,名为DBTYPE
             valueFrom:											#valueFrom表示变量值来自哪里
               configMapKeyRef:									#表示引用的是ConfigMap
                 name: my-config								#指定来源于my-config
                 key: dbtype									#指定来自my-config的名称为dbtype的key
           - name: IP											#环境变量,名为IP
             valueFrom:											#valueFrom表示变量值来自哪里
               configMapKeyRef:									#表示引用的是ConfigMap
                 name: my-config								#指定来源于my-config
                 key: ip										#指定来自my-config的名称为ip的key
           - name: PORT											#环境变量,名为PORT
             valueFrom:											#valueFrom表示变量值来自哪里
               configMapKeyRef:									#表示引用的是ConfigMap
                 name: my-config								#指定来源于my-config
                 key: port										#指定来自my-config的名称为port的key
           ports:
           - name: http 
             containerPort: 80

挂载

ConfigMap最主要的功能就是向容器传递配置文件,所以,kubernetes主要使用ConfigMap卷的形式将条目暴露为容器内的文件从而来实现向容器传递配置文件。

configMap卷会将configmap资源对象中的每个条目暴露成一个文件,这样运行在容器中的进程就可以通过读取文件的内容来获取对应的条目值。

覆盖

ConfigMap my-config4 里有两条数据,一条由字面量创建,一条由文件创建。

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-cm-configmapvolume
  namespace: killer
spec:
  replicas: 1
  selector:
     matchLabels:
         app: nginx-cm-configmapvolume
  template:
     metadata:
       labels:
         app: nginx-cm-configmapvolume
     spec:
         containers:
         - image: nginx:1.29-alpine-slim
           imagePullPolicy: IfNotPresent
           name: nginx-container
           volumeMounts:								#定义挂载点
           - name: configmap-volume						#挂载的卷的名称
             mountPath: /etc/config/					#挂载目录
           ports:
           - name: http 
             containerPort: 80
         volumes:										#定义卷
         - name: configmap-volume						#卷的名称
           configMap:									#表示这是一个configmap卷
             name: my-config4							#卷定义引用名为my-config4的configmap资源对象

apply该deployment,查看容器内文件,以两条数据的键名形成配置文件。

root@k8s1:~/configmap# kubectl exec deployment-nginx-cm-configmapvolume-59d97bd754-vvpnd -n killer -- ls -l /etc/config/
total 0
lrwxrwxrwx    1 root     root            11 Aug 27 02:39 type -> ..data/type
lrwxrwxrwx    1 root     root            20 Aug 27 02:39 ui.properties -> ..data/ui.properties

文件内是每条数据的值。

root@k8s1:~/configmap# kubectl exec deployment-nginx-cm-configmapvolume-59d97bd754-vvpnd -n killer -- cat /etc/config/type
html
root@k8s1:~/configmap# kubectl exec deployment-nginx-cm-configmapvolume-59d97bd754-vvpnd -n killer -- cat /etc/config/ui.properties
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

如果只挂载某个key,需使用items

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-cm-configmapvolume-item
  namespace: killer
spec:
  replicas: 1
  selector:
     matchLabels:
         app: nginx-cm-configmapvolume-item
  template:
     metadata:
       labels:
         app: nginx-cm-configmapvolume-item
     spec:
         containers:
         - image: nginx:1.29-alpine-slim
           imagePullPolicy: IfNotPresent
           name: nginx-container
           volumeMounts:								#定义挂载点
           - name: configmap-volume						#挂载的卷的名称
             mountPath: /etc/config/					#挂载目录
           ports:
           - name: http 
             containerPort: 80
         volumes:										#定义卷
         - name: configmap-volume						#卷的名称
           configMap:									#表示这是一个configmap卷
             name: my-config4							#卷定义引用名为my-config4的configmap资源对象
             items:
               - key: ui.properties
                 path: path/to/ui.properties

在/etc/config/path/to下仅发现 ui.properties。

root@k8s1:~/configmap# kubectl exec deployment-nginx-cm-configmapvolume-item-798cbcd7f4-6r229 -n killer  -- ls -l /etc/config/path/to
total 4
-rw-r--r--    1 root     root            81 Aug 27 06:12 ui.properties

修改ConfigMap,可以实现应用实时更新配置(以configmap卷挂载的,能实现更新)

data:
  type: html
  ui.properties: |
    color.good=purple
    color.bad=blue   # 修改color.bad为blue
    allow.textmode=true
    how.nice.to.look=fairlyNice

等待一会儿,查看容器是否更新了,如下所示,说明configmap卷挂载的,当修改ConfigMap时,容器时可以读取到最新的配置的。

但是注意一点,虽然容器内的配置文件是更新了的,但并不能保证应用程序是否读取了最新的配置文件内容,这取决于应用程序是否实时监听

配置文件,比如nginx程序,nginx程序就不能动态读取配置文件,还需要nginx -s reload

root@k8s1:~/configmap# kubectl exec deployment-nginx-cm-configmapvolume-59d97bd754-vvpnd -n killer -- cat /etc/config/ui.properties
color.good=purple
color.bad=blue
allow.textmode=true
how.nice.to.look=fairlyNice

[!IMPORTANT]

使用configmap卷的形式挂载了configmap资源对象的所有条目到容器内的某个目录,从Linux挂载的概念我们得知,当挂载点存在文件时,那么挂载点之前存在的文件就会被隐藏,有时候这一点Linux的特性会造成严重后果,如当挂载到/etc目录时就会造成/etc目录下的所有配置文件被隐藏,这样程序就会出问题.

Subpath

subpath允许configmap卷挂载configmap的单独条目为文件被挂载且不隐藏原目录中的其他文件(这种方式的挂载不能实现热更新)。

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-cm-configmapvolume-all-item
  namespace: killer
spec:
  replicas: 1
  selector:
     matchLabels:
         app: nginx-cm-configmapvolume-all-item
  template:
     metadata:
       labels:
         app: nginx-cm-configmapvolume-all-item
     spec:
         containers:
         - image: nginx:1.29-alpine-slim
           imagePullPolicy: IfNotPresent
           name: nginx-container
           volumeMounts:								#定义挂载点
           - name: configmap-volume						#挂载的卷的名称
             mountPath: /etc/ui.properties				#挂载到某一文件,文件名可以自己定义
             subPath: ui.properties                     #表示挂载ui.properties条目,必须是my-config4的条目名
           ports:
           - name: http 
             containerPort: 80
         volumes:										#定义卷
         - name: configmap-volume						#卷的名称
           configMap:									#表示这是一个configmap卷
             name: my-config4							#卷定义引用名为my-config4的configmap资源对象

查看pod里的/etc目录,发现ui.properties文件,且其他目录文件保留

root@k8s1:~/configmap# kubectl exec deployment-nginx-cm-configmapvolume-al-item-f95bf6dc9-fd8fr -n killer -- ls -l /etc
total 176
-rw-r--r--    1 root     root             7 Jul 15 10:41 alpine-release
drwxr-xr-x    1 root     root          4096 Aug 13 18:52 apk
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 busybox-paths.d
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 crontabs
-rw-r--r--    1 root     root            89 Mar 25 13:16 fstab
-rw-r--r--    1 root     root           528 Aug 13 18:52 group
-rw-r--r--    1 root     root           523 Aug 13 18:52 group-
-rw-r--r--    1 root     root            60 Aug 27 05:48 hostname
-rw-r--r--    1 root     root           253 Aug 27 05:48 hosts
drwxr-xr-x    2 root     root          4096 Aug 13 18:52 init.d
-rw-r--r--    1 root     root           570 Mar 25 13:16 inittab
-rw-r--r--    1 root     root            51 Jul 15 10:41 issue
drwxr-xr-x    1 root     root          4096 Aug 13 18:52 logrotate.d
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 modprobe.d
-rw-r--r--    1 root     root            15 Mar 25 13:16 modules
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 modules-load.d
-rw-r--r--    1 root     root           284 Mar 25 13:16 motd
lrwxrwxrwx    1 root     root            14 Jul 15 10:42 mtab -> ../proc/mounts
drwxr-xr-x    8 root     root          4096 Jul 15 10:42 network
drwxr-xr-x    1 root     root          4096 Aug 13 18:52 nginx
-rw-r--r--    1 root     root           205 Mar 25 13:16 nsswitch.conf
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 opt
lrwxrwxrwx    1 root     root            21 Jul 15 10:42 os-release -> ../usr/lib/os-release
-rw-r--r--    1 root     root           755 Aug 13 18:52 passwd
-rw-r--r--    1 root     root           702 Mar 25 13:16 passwd-
drwxr-xr-x    7 root     root          4096 Jul 15 10:42 periodic
-rw-r--r--    1 root     root           547 Mar 25 13:16 profile
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 profile.d
-rw-r--r--    1 root     root          3144 Mar 25 13:16 protocols
-rw-r--r--    1 root     root           102 Aug 27 05:48 resolv.conf
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 secfixes.d
-rw-r--r--    1 root     root           156 May 26 20:04 securetty
-rw-r--r--    1 root     root         12813 Mar 25 13:16 services
-rw-r-----    1 root     shadow         287 Aug 13 18:52 shadow
-rw-r-----    1 root     shadow         260 Jul 15 10:42 shadow-
-rw-r--r--    1 root     root            38 Mar 25 13:16 shells
drwxr-xr-x    4 root     root          4096 Jul 15 10:42 ssl
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 ssl1.1
-rw-r--r--    1 root     root            53 Mar 25 13:16 sysctl.conf
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 sysctl.d
drwxr-xr-x    2 root     root          4096 Jul 15 10:42 udhcpc
-rw-r--r--    1 root     root            81 Aug 27 05:48 ui.properties
深度解析mountPath,subPath,key,path的关系和作用

kubernetes key (pod.spec.volums[0].configMap.items[0].key)用于指定configMap中的哪些条目可用于挂载

kubernetes path (pod.spec.volums[0].configMap.items[0].path)用于将key重命名

kubernetes subPath (pod.spec.containers[0].volumeMounts.subPath)决定容器中有无挂载(按名字从key,有path时以path为主,中比对是否存在要的条目)。

kubernetes mountPath (pod.spec.containers[0].volumeMounts.mountPath)决定容器中挂载的结果文件名。没有subPath项时,此项仅指定路径。有subPath时且subPath筛选结果为true时,此项指定路径和文件名,此时文件名可随意指定;有subPath但subPath筛选结果为false时,此项指定路径(最后一级目录名为文件名)

Secret

Secret 资源的功能类似于 ConfigMap,但它专用于存放敏感数据,例如密码、数字证书、私钥、令牌 和 SSH key 等。

Secret 对象存储数据的方式及使用方式类似于 ConfigMap 对象,相同的是,都以键值方式存储数据,在 Pod 资源中通过环境变量或存储卷进行数据访问。不同的是,Secret 对象仅会被分发至调用了对象的 Pod 资源所在的工作节点,且只能由节点将其存储于内存中。另外,Secret 对象的数据的存储及打印格式为 Base64 编码的字符串,因此用户创建 Secret 对象时也要提供此编码格式的数据。在容器中以环境变量或存储卷的方式访问时,它们会被自动解码为明文格式。

需要注意的是,在 Master 节点上,Secret 对象以非加密的格式存储于 etcd 中,因此管理员必须加以精心管控以确保敏感数据的机密性,必须确保 etcd 集群节点间以及与 API Server 的安全通信,etcd 服务的访问授权,还包括用户访问 API Server 时的授权,因为拥有创建 Pod 资源的用户都可以使用 Secret 资源并能够通过 Pod 的容器访问其数据。

Secret 资源主要由四种类型组成,具体如下:

  • Opaque: 自定义数据内容:base64编码,用来存储密码、密钥、信息、证书等数据。
  • kubernetes.io/tls: 用于为 SSL 通信模式存储证书和私钥文件,命令式创建时类型表示为 tls。
  • kubernetes.io/dockerconfigjson: 用来存储 Docker 镜像仓库的认证信息,类型标识为 docker-registry。
  • kubernetes.io/servcie-account-token: Servcie Account 的认证信息,可在创建 Service Account 时由 Kubernetes 自动创建。

以下主要介绍Opaque和docker-registry两种常用类型。

Opaque

Opaque是最常用且默认类型的Secret,其数据通过base64编码存储。Opaque类型的Secret目的跟ConfigMap一样,其创建和使用也跟ConfigMap一样。

分别base64编码用户名admin和密码admin123

root@k8s1:~/configmap# echo -n 'admin' | base64
YWRtaW4=
root@k8s1:~/configmap# echo -n 'admin123' | base64
YWRtaW4xMjM=

创建secret.yaml

apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  username: YWRtaW4=
  password: YWRtaW4xMjM=

也可以用命令行创建,此时无需先base64编码,生成secret后会自动加密,而非明文存储。

kubectl create secret generic mysecret --from-literal=username=admin --from-literal=password=admin123

生成secret,并查看状态

root@k8s1:~/secret# kubectl get secret -oyaml
apiVersion: v1
items:
- apiVersion: v1
  data:
    password: YWRtaW4xMjM=
    username: YWRtaW4=
  kind: Secret
  metadata:
    annotations:
      kubectl.kubernetes.io/last-applied-configuration: |
        {"apiVersion":"v1","data":{"password":"YWRtaW4xMjM=","username":"YWRtaW4="},"kind":"Secret","metadata":{"annotations":{},"name":"mysecret","namespace":"default"},"type":"Opaque"}
    creationTimestamp: "2025-08-27T07:03:39Z"
    name: mysecret
    namespace: default
    resourceVersion: "7995772"
    uid: 2ddd73ff-88ac-438f-8cd3-6eef2430b1f6
  type: Opaque
kind: List
metadata:
  resourceVersion: ""

将Secret挂载到Volume中

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-secret-volume
  namespace: default
spec:
  replicas: 1
  selector:
     matchLabels:
         app: nginx-secret-volume
  template:
     metadata:
       labels:
         app: nginx-secret-volume
     spec:
         containers:
         - image: nginx:1.29-alpine-slim
           imagePullPolicy: IfNotPresent
           name: nginx-container
           volumeMounts:								#定义挂载点
           - name: secret-volume						#挂载的卷的名称
             mountPath: /etc/secret/					#挂载目录
           ports:
           - name: http 
             containerPort: 80
         volumes:										#定义卷
         - name: secret-volume						#卷的名称
           secret:									#表示这是一个secret卷
             secretName: mysecret							#卷定义引用名为mysecret的secret资源对象

查看/etc/secret/目录,发现有password和username两个文件,文件内为明码的数据。

root@k8s1:~/secret# kubectl exec deployment-nginx-secret-volume-5677bc7c8f-mcb5p -- ls -l /etc/secret
total 0
lrwxrwxrwx    1 root     root            15 Aug 27 07:40 password -> ..data/password
lrwxrwxrwx    1 root     root            15 Aug 27 07:40 username -> ..data/username
root@k8s1:~/secret# kubectl exec deployment-nginx-secret-volume-5677bc7c8f-mcb5p -- cat /etc/secret/username
admin

将Secret作为环境变量提供。

apiVersion: apps/v1
kind: Deployment
metadata: 
  name: deployment-nginx-secret-env
  namespace: default
spec:
  replicas: 1
  selector:
     matchLabels:
         app: nginx-secret-env
  template:
     metadata:
       labels:
         app: nginx-secret-env
     spec:
         containers:
         - image: nginx:1.29-alpine-slim
           name: nginx-container
           env:
           - name: SECRET_USERNAME										#环境变量,名为SECRET_USERNAME
             valueFrom:											#valueFrom表示变量值来自哪里
               secretKeyRef:									#表示引用的是secret
                 name: mysecret								#指定来源于mysecret
                 key: username									#指定来自mysecret的名称为username的key
           - name: 											#环境变量,名为IP
             valueFrom:	SECRET_PASSWORD
               secretKeyRef:
                 name: mysecret
                 key: password
           ports:
           - name: http 
             containerPort: 80

进入容器查看env

root@k8s1:~/secret# kubectl exec -it deployment-nginx-secret-env-646766b55d-q42p7 -- /bin/sh
/ # env
KUBERNETES_SERVICE_PORT=443
KUBERNETES_PORT=tcp://10.96.0.1:443
HOSTNAME=deployment-nginx-secret-env-646766b55d-q42p7
SHLVL=1
HOME=/root
PKG_RELEASE=1
SECRET_PASSWORD=admin123  ### secret信息
DYNPKG_RELEASE=1
TERM=xterm
NGINX_VERSION=1.29.1
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
SECRET_USERNAME=admin   ### secret信息
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_HOST=10.96.0.1
PWD=/

docker-registry

创建docker_registry类型的secret

kubectl create secret docker-registry -n external my-registry-secret \
--docker-server=os-harbor-svc.default.svc.cloudos:443 \
--docker-username=unicloud \
--docker-password=Unicloud@123! \
--docker-email=unicloud@unicloud.com

创建应用时调用此secret

apiVersion: apps/v1
kind: Deployment
metadata:
  name: deployment-secret-registry
  namespace: external
spec:
  replicas: 1
  selector:
     matchLabels:
         app: deployment-secret-registry
  template:
    metadata:
       labels:
         app: deployment-secret-registry
    spec:
      containers:
      - name: myapp
        image: os-harbor-svc.default.svc.cloudos:443/external/nginx:1.29  #镜像地址]
        resources:
          limits:
            cpu: '2'
            memory: 4Gi
          requests:
            cpu: '2'
            memory: 4Gi
        ports:
        - containerPort: 80
      imagePullSecrets:
      - name: myregistrysecret  # docker_registry类型的secret,实现拉取镜像时认证
posted @ 2025-11-19 11:09  VitoChen  阅读(14)  评论(0)    收藏  举报