前言
使用场景:配置文件
应用程序的运行可能会依赖一些配置,而这些配置又是可能会随着需求产生变化的,如果我们的应用程序架构不是应用和配置分离的,那么就会存在当我们需要去修改某些配置项的属性时需要构建镜像文件的窘境,configmap组件可以实现应用和配置分离,避免因为修改配置项而重新构建镜像。用于保存配置数据的键值对,也可以保存配置文件或单个属性。
注意:
• configMap必须在pod引用它之前创建
• 使用envFrom时,将会自动忽略无效的键
• pod只能使用同一个命名空间内的configmap
• configmap挂载文件时,会先覆盖掉挂载目录,然后再将configmap中的内容作为文件挂载,若不想对原来的文件夹下的文件造成覆盖,可以使用subpath参数。
配置实践
1、创建配置文件,再创建configMap
[root@k8s-master ~]# cat redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
[root@k8s-master ~]# kubectl create cm redis-config --from-file=redis.properties
configmap/redis-config created
[root@k8s-master ~]# kubectl get cm
NAME DATA AGE
kube-root-ca.crt 1 5d23h
redis-config 1 7s
[root@k8s-master ~]# kubectl describe cm redis-config
Name: redis-config
Namespace: default
Labels: <none>
Annotations: <none>
Data
====
redis.properties:
----
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
BinaryData
====
Events: <none>
2、以volume形式挂载pod
[root@k8s-master ~]# cat cm-vol.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: busybox
image: busybox:1.28
command: ["/bin/sh","-c","cat /etc/config/redis.properties"]
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
name: redis-config
restartPolicy: Never
[root@k8s-master ~]# kubectl apply -f cm-vol.yaml
pod/mypod created
[root@k8s-master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
mypod 0/1 Completed 0 6s
[root@k8s-master ~]# kubectl logs mypod
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
3、以变量形式挂载pod:先创建configmap,声明变量,在进行变量挂载
[root@k8s-master ~]# cat cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: myconfig
namespace: default
data:
special.level: info
special.type: hello
[root@k8s-master ~]# kubectl apply -f cm.yaml
configmap/myconfig created
[root@k8s-master ~]# kubectl get cm
NAME DATA AGE
kube-root-ca.crt 1 5d23h
myconfig 2 5s
redis-config 1 13m
[root@k8s-master ~]# cat cm-val.yaml
apiVersion: v1
kind: Pod
metadata:
name: yypod
spec:
containers:
- name: busybox
image: busybox:1.28
command: ["/bin/sh","-c","echo $(LEVEL) $(TYPE)"]
env:
- name: LEVEL
valueFrom:
configMapKeyRef:
name: myconfig
key: special.level
- name: TYPE
valueFrom:
configMapKeyRef:
name: myconfig
key: special.type
restartPolicy: Never
[root@k8s-master ~]# kubectl apply -f cm-val.yaml
pod/yypod created
[root@k8s-master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
mypod 0/1 Completed 0 16m
yypod 0/1 Completed 0 5s
[root@k8s-master ~]# kubectl logs yypod
info hello