5.1.k8s.ConfigMap

ConfigMap

ConfigMap用于保存配置数据的键值对,可用来保存单个属性,或配置文件

#ConfigMap创建

使用yaml文件创建ConfigMap

#cm-demo.yaml
kind: ConfigMap
apiVersion: v1
metadata:
  name: cm-demo
  namespace: default
data:
  data.1: hello
  data.2: world
  config: |
    property.1=value-1
    property.2=value-2
#创建
kubectl create -f cm-demo.yaml.yaml
#查看
kubectl get cm cm-demo -o yaml

从文件、目录创建ConfigMap

#创建目录和文件
mkdir testcm
echo -e "host=127.0.0.1\nport=3306" >testcm/mysql.conf
echo -e "host=127.0.0.1\nport=6379" >testcm/redis.conf
ls -l  testcm
cat testcm/mysql.conf
cat testcm/redis.conf
#使用from-file 从目录testcm 创建ConfigMap 名称为cm-demo1
kubectl create configmap cm-demo1 --from-file=testcm
#查看cm
#kubectl get configmap
kubectl get cm
#查看详情
kubectl describe configmap cm-demo1
kubectl get configmap cm-demo1 -o yaml

key-value字符串创建ConfigMap

#通过--from-literal参数,从字符串创建ConfigMap
kubectl create configmap cm-demo2  \
--from-literal=db.host=localhost --from-literal=db.port=3306
#查看
kubectl get configmap cm-demo2 -o yaml

kubectl get cm
kubectl delete cm cm-demo3

#ConfigMap使用

ConfigMap在Pod使用方式: 环境变量、命令行参数、数据卷Volume
ConfigMap 挂载的 Env 不会同步更新

env方式挂载 (环境变量、命令行参数使用)

# cm1-pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: cm1-pod
spec:
  containers:
    - name: cm1
      image: busybox:uclibc
      command: [ "/bin/sh", "-c", "env" ]
      #command: [ "/bin/sh", "-c", "echo $(DB_HOST) $(DB_PORT)" ] #命令行参数
      env:
        - name: DB_HOST
          valueFrom:
            configMapKeyRef:
              name: cm-demo2
              key: db.host
        - name: DB_PORT
          valueFrom:
            configMapKeyRef:
              name: cm-demo2
              key: db.port
      envFrom:
        - configMapRef:
            name: cm-demo1
  restartPolicy: Never
#创建
kubectl create -f cm1-pod.yaml
#查看
kubectl logs cm1-pod

Volume方式挂载

#cm2-pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: cm2-pod
spec:
  containers:
    - name: cm2
      image: busybox:uclibc
      command: [ "/bin/sh", "-c", "cat /test/redis.conf" ]
      volumeMounts:
      - name: config-volume
        mountPath: /test
  volumes:
    - name: config-volume
      configMap:
        name: cm-demo1
  restartPolicy: Never
#创建
kubectl create -f cm2-pod.yaml
#查看
kubectl logs cm2-pod

清理demo

kubectl delete -f cm1-pod.yaml
kubectl delete -f cm2-pod.yaml
kubectl delete cm cm-demo
kubectl delete cm cm-demo1
kubectl delete cm cm-demo2

参考https://www.qikqiak.com/k8s-book/docs/28.ConfigMap.html


Blog地址 https://www.cnblogs.com/elvi/p/11755789.html
本文git地址 https://gitee.com/alivv/k8s/tree/master/notes

posted @ 2019-10-28 22:22  Elvin-vip  阅读(497)  评论(0编辑  收藏  举报
https://rpc.cnblogs.com/metaweblog/elvi