508.【kubernetes】ConfigMap: 在 Pod 中挂载文件(非目录)

一、创建并启动 ConfigMap

  1. 方法一:
[root@k8s0 test_config_map]# cat >cm-qijing.yaml <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: cm-qijing
data:
  key-qijing-file.txt: |
    from key-qijing-file.txt
    hello qijing

EOF
  1. 方法二:
[root@k8s0 test_config_map]# cat >key-qijing-file.txt <<EOF
from key-qijing-file.txt
hello qijing
EOF
[root@k8s0 test_config_map]# kubectl create cm cm-qijing --from-file=./key-qijing-file.txt 
configmap/cm-qijing created
  • 两种方式的结果都是一样的

二、挂载ConfigMap中的文件,创建并启动 Pod

[root@k8s0 test_config_map]# cat test-cm-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: cm-test-pod
spec:
  containers:
  - name: cm-test
    image: busybox
    command: ["ls", "-l", "/tmp"]
    volumeMounts:
    - name: example
      mountPath: /tmp/key-qijing-file.txt
      subPath: key-qijing-file.txt
  volumes:
  - name: example
    configMap:
      name: cm-qijing
      items:
      - key: key-qijing-file.txt
        path: key-qijing-file.txt
  restartPolicy: Never
[root@k8s0 test_config_map]# kubectl create -f test-cm-pod.yaml 
pod/cm-test-pod created
[root@k8s0 test_config_map]# kubectl get po
NAME          READY   STATUS              RESTARTS   AGE
cm-test-pod   0/1     ContainerCreating   0          3s
[root@k8s0 test_config_map]# kubectl get po
NAME          READY   STATUS      RESTARTS   AGE
cm-test-pod   0/1     Completed   0          4s
[root@k8s0 test_config_map]# kubectl get po
NAME          READY   STATUS      RESTARTS   AGE
cloudwavedb   1/1     Running     0          38m
cm-test-pod   0/1     Completed   0          4s
[root@k8s0 test_config_map]# kubectl logs -f cm-test-pod
total 4
-rw-r--r--    1 root     root            38 Nov 27 03:59 key-qijing-file.txt
  • 可以看到在容器内部已经能看到通过 ConfigMap 挂载的文件了。这个ConfigMap也是一个应用程序的配置文件解决方案。

三、使用 ConfigMap 的限制条件

  • ConfigMap 必须在 Pod 之前创建,Pod 才能引用它。
  • 如果 Pod 使用 envFrom 基于 ConfigMap 定义环境变量,则无效的变量名称将被忽略,并在事件中被记录为 InvalidVariableNames。
  • ConfigMap 受命名空间限制,只有处于相同命名空间中的 Pod 才可以引用它。
  • ConfigMap 无法用于静态 Pod。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容