参考视频:https://ke.qq.com/user/index/index.html#/plan/cid=1709963&term_id=102815140

一、概念

创建ConfigMap后,数据实际会存储在K8s(Etcd)中,然后通过创建Pod时引用该数据。

Pod使用ConfigMap挂载的两种方式

  • 变量注入

  • 数据卷挂载

二、实例

2.1.创建一个configmap

方式一:

apiVersion: v1
kind: ConfigMap
metadata:
  name: redis-cfg
data:
  #以键值对的形式定义
  abc: "123"
  bcd: "456"

  #以文本的形式定义,适用于多行文件;|表示支持多行
  redis.properties: |
    port: 6379
    host: 192.168.1.10

方式二:指定文件生成并创建configmap

kubectl create cm myconfigmap --from-file=application.yml -n mynamespace

2.2.Pod使用configmap

apiVersion: v1
kind: Pod
metadata:
  name: configmap-demo-pod
spec:
  containers:
    - name: demo
      image: nginx
      imagePullPolicy: IfNotPresent
      env:
      - name: ABC
        valueFrom:
          configMapKeyRef:
            name: redis-cfg
            key: abc
      - name: BCD
        valueFrom:
          configMapKeyRef:
            name: redis-cfg
            key: bcd
      volumeMounts:
      - name: config					#卷名
        mountPath: "/config"			#挂载到容器的/config目录下
        readOnly: true
  volumes:
    - name: config						#卷名
      configMap:
        name: redis-cfg					#configmap的名字
        items:
        - key: "redis.properties"		#configmap中的文件名
          path: "redis_config"			#挂载到容器后的文件名

进入到容器中查看
在这里插入图片描述

三、subPath

参考文章:
K8s subPath

volumeMounts:
- name: nginx-config
  mountPath: /etc/nginx/nginx.conf # 也可挂载到文件
  subPath: nginx.conf # 挂载到文件时,需设置子路径

将名为 nginx-config的 volume 中的 nginx.conf key 对应内容,以文件形式挂载到容器中 /etc/nginx/nginx.conf 路径。

需注意:在 ConfigMap 中使用 subPath 将影响 ConfigMap 内容变化时的自动更新。

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐