如何创建一个挂载文件的卷,该文件的路径在 ConfigMap 中配置

How to create a volume that mounts a file which it's path configured in a ConfigMap

我将描述我的目标是什么,然后展示我为实现它所做的工作...我的目标是:

我做了什么:

配置图:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  my_properties_file_name: "my.properties"

部署:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-client-deployment
spec:
  selector:
    matchLabels:
      app: my-client
  replicas: 1 # tells deployment to run 2 pods matching the template
  template:
    metadata:
      labels:
        app: my-client
    spec:
      containers:
      - name: my-client-container
        image: {{ .Values.image.client}}
        imagePullPolicy: {{ .Values.pullPolicy.client }}
        ports:
        - containerPort: 80
        env:
        - name: MY_PROPERTIES_FILE_NAME
          valueFrom:
            configMapKeyRef:
              name: my-configmap
              key: my_properties_file_name
        volumeMounts:
        - name: config
          mountPath: "/etc/config"
          readOnly: true
      imagePullSecrets:
      - name: secret-private-registry  
      volumes:
      # You set volumes at the Pod level, then mount them into containers inside that Pod
      - name: config
        configMap:
          # Provide the name of the ConfigMap you want to mount.
          name: my-configmap
          # An array of keys from the ConfigMap to create as files
          items:
          - key: "my_properties_file_name"
            path: "my.properties"

结果是在 /etc/config 下有一个名为 my.properties 的文件,但该文件的内容是“my.properties”(因为它在 configmap 中表示为文件名),而不是我在本地磁盘中实际拥有的属性文件的内容。

如何使用在 configmap 中配置的路径装载该文件?

my.properties文件的内容直接放在ConfigMap中:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  my_properties_file_name: |
    This is the content of the file.
    It supports multiple lines but do take care of the indentation.

或者您也可以使用 kubectl create configmap 命令:

kubectl create configmap my-configmap --from-file=my_properties_file_name=./my.properties

无论哪种方式,实际上都是将本地磁盘上文件内容的快照传递给kubernetes存储。除非您重新创建配置映射,否则您对本地磁盘上的文件所做的任何更改都不会反映出来。

kubernetes 的设计允许对位于地球另一端的 kubernetes 集群执行 运行 kubectl 命令,因此您不能简单地在本地磁盘上挂载文件以供实时访问集群。如果你想要这样的机制,你不能使用 ConfigMap,而是你需要设置一个共享卷,由你的本地机器和集群挂载,例如使用 NFS 服务器。