ConfigMap提供了向容器中注入配置信息的能力,不仅可以用来保存单个属性,也可以用来保存整个配置文件,比如可以用来配置一个redis服务的访问地址,也可以用来保存整个redis的配置文件。

创建

kubectl create configmap <configmap name> --from-file=文件路径

配置文件内容格式key=value

kubectl create configmap <configmap name> --from-literal=<key=value>

查询

kubectl get configmap

kubectl describe configmap <configmap name>

kubectl get configmap <configmap name> -o yaml #格式化查看键值

使用

设置环境变量的值

apiVersion: v1 
kind: Pod
metadata:
name: testcm1-pod
spec:
containers:
- name: testcm1
image: busybox
command: [ "/bin/sh", "-c", "env" ]
env:
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: cm-demo3 #configmap name
key: db.host #key name
- name: DB_PORT
valueFrom:
configMapKeyRef:
name: cm-demo3 #configmap name
key: db.port #key name
envFrom:
- configMapRef:
name: cm-demo1 #configmap name

设置命令行参数

apiVersion: v1 
kind: Pod
metadata:
name: testcm2-pod
spec:
containers:
- name: testcm2
image: busybox
command: [ "/bin/sh", "-c", "echo $(DB_HOST) $(DB_PORT)" ]
env:
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: cm-demo3
key: db.host
- name: DB_PORT
valueFrom:
configMapKeyRef:
name: cm-demo3
key: db.port

在数据卷里面创建config文件

apiVersion: v1 
kind: Pod
metadata:
name: testcm3-pod
spec:
containers:
- name: testcm3
image: busybox
command: [ "/bin/sh", "-c", "cat /etc/config/redis.conf" ]
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: cm-demo2

验证

kubectl logs <pod name> #查看输出