ConfigMap 安装在 Persistent Volume Claims 上

ConfigMap mounted on Persistent Volume Claims

在我的部署中,我想将 Persistent Volume Claim 与配置映射挂载结合使用。例如,我想要以下内容:

volumeMounts:
    - name: py-js-storage
        mountPath: /home/python
    - name: my-config
        mountPath: /home/python/my-config.properties
        subPath: my-config.properties
        readOnly: true
...
    volumes:
    - name: py-storage
    {{- if .Values.py.persistence.enabled }}
        persistentVolumeClaim:
        claimName: python-storage
    {{- else }}
        emptyDir: {}
    {{- end }}

这是可行且可行的方法吗?有没有更好的方法来处理这种情况?

既然你没有给出你的用例,我的回答将基于是否可能。事实上:是的,它是。

我假设您希望从 configMap 挂载文件到已经包含其他文件的挂载点,并且您使用 subPath 的方法是正确的!

当你需要在同一个路径下挂载不同的卷时,需要指定subPath否则原目录的内容会被隐藏.

换句话说,如果你想保留两个文件(来自 configMap 的挂载点 )你 必须 使用 subPath.

为了说明这一点,我使用下面的部署代码进行了测试。我在那里挂载了 hostPath /mnt,它在我的 pod 中包含一个名为 filesystem-file.txt 的文件,在我的 configmap test-pd-plus-cfgmap:

中包含一个名为 /mnt/configmap-file.txt 的文件

Note: I'm using Kubernetes 1.18.1

配置图:

apiVersion: v1
kind: ConfigMap
metadata:
  name: test-pd-plus-cfgmap
data:
  file-from-cfgmap: file data

部署:


apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-pv
spec:
  replicas: 3
  selector:
    matchLabels:
      app: test-pv
  template:
    metadata:
      labels:
        app: test-pv
    spec:
      containers:
      - image: nginx
        name: nginx
        volumeMounts:
        - mountPath: /mnt
          name: task-pv-storage
        - mountPath: /mnt/configmap-file.txt
          subPath: configmap-file.txt
          name: task-cm-file
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
            claimName: task-pv-claim
        - name: task-cm-file
          configMap:
            name: test-pd-plus-cfgmap

部署后,在pod的/mnt中可以看到如下内容:

$ kubectl exec test-pv-5bcb54bd46-q2xwm -- ls /mnt
configmap-file.txt
filesystem-file.txt

你可以用同样的讨论检查这个githubissue

Here 你可以阅读更多关于卷的内容 subPath

您可以采用以下方法。

在您的 deployment.yaml 模板文件中,您可以配置:

...
{{- if .Values.volumeMounts }}
        volumeMounts:
{{- range .Values.volumeMounts }}
        - name: {{ .name }}
          mountPath: {{ .mountPath }}
{{- end }}
{{- end }}
...
{{- if .Values.volumeMounts }}
      volumes:
{{- range .Values.volumeMounts }}
      - name: {{ .name }}
{{ toYaml .volumeSource | indent 8 }}
{{- end }}
{{- end }}

而您的 values.yaml 文件您可以定义任何卷来源:

volumeMounts:
  - name: volume-mount-1
    mountPath: /var/data
    volumeSource:
      persistentVolumeClaim:
        claimName: pvc-name
  - name: volume-mount-2
    mountPath: /var/config
    volumeSource:
      configMap:
        name: config-map-name

这样一来,您就不用担心音量的来源了。您可以在 values.yaml 文件中添加任何类型的来源,而不必更新 deployment.yaml 模板。

希望对您有所帮助!