说明
ConfigMap是一种比较特殊的存储卷,它的主要作用是用来存储配置信息的。
应用场景
在 springcloud 微服务中,此功能可以 代替 配置中心
例子
创建 configmap 配置文件
创建 configmap.yaml
vim configmap.yaml
按 i 键
复制粘贴下面内容:
apiVersion: v1
kind: ConfigMap # 表示 存储配置信息
metadata:
name: configmap # ConfigMap 的名字(关键)
namespace: test
data:
db.conf: | # 配置的名字,挂载到pod后,是配置文件的名字
username:root # mysql 用户名,挂载到pod后,是配置文件中的内容
password:123456 # mysql 密码,挂载到pod后,是配置文件中的内容
按 esc,:wq 保存退出
创建configmap
kubectl create -f configmap.yaml
执行结果如下:
configmap/configmap created
查看configmap详情
kubectl describe cm configmap -n test
显示结果如下:
Name: configmap
Namespace: test
Labels: <none>
Annotations: <none>
Data
====
db.conf:
----
username:root # mysql 用户名
password:123456 # mysql 密码
Events: <none>
创建 pod 配置文件
vim pod-configmap.yaml
按 i 键
复制粘贴下面内容:
apiVersion: v1
kind: Pod
metadata:
name: pod-configmap
namespace: test
spec:
containers:
- name: nginx
image: nginx:1.17.1
volumeMounts: # 配置挂载信息
- name: config # 指明下面 volumes 的 name
mountPath: /config # 挂载到容器的目录
volumes: # 引用configmap
- name: config # 名字,此处任意起
configMap:
name: configmap # 是configmap.yaml ConfigMap 的名字(关键)
按 esc,:wq 保存退出
创建pod
kubectl create -f pod-configmap.yaml
执行结果如下:
pod/pod-configmap created
查看pod
kubectl get pod -n test
NAME READY STATUS RESTARTS AGE
pod-configmap 1/1 Running 0 6s
进入容器查看配置
kubectl exec -it pod-configmap -n test /bin/sh
cd /config/
ls
db.conf
cat db.conf
显示结果如下:
username:root # mysql 用户名
password:123456 # mysql 密码
可以看到映射已经成功,每个configmap都映射成了一个目录
key—->文件 value——>文件中的内容
修改 configmap 配置文件
如果更新configmap的内容, 容器中的值也会动态更新
创建 configmap 配置文件
修改 configmap.yaml
kubectl edit cm configmap -n test
按 i 键
将密码改为 root
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
data:
db.conf: |
username:root # mysql 用户名
password:root # mysql 密码
kind: ConfigMap
metadata:
creationTimestamp: "2023-10-02T14:39:46Z"
name: configmap
namespace: test
resourceVersion: "940928"
selfLink: /api/v1/namespaces/test/configmaps/configmap
uid: 8642c5ca-cdd0-4346-b043-729defd53dce
按 esc,:wq 保存退出
等待 1-3分钟 左右,再次查看配置文件
cat db.conf
显示结果如下:
username:root # mysql 用户名
password:root # mysql 密码