Kubernets——subPath介绍


前言

  subPath做为volumeMounts的配置参数实现了指定所引用的卷内的子路径,而不是其根路径。即在单个共享卷以供多个pod方使用是很有用的。


一、subPath

  subPath字段允许在PVC的挂载路径中指定一个子目录,而不是将整个PVC的内容直接挂载到Pod的目录中。这样,可以更灵活地控制Pod中使用哪些文件和目录。
  volume支持将configMap/secret挂载到容器的路径,但是会覆盖容器路径下原有的文件。如何支持选定configmap/secret的key-value挂载到容器中,且不会覆盖掉原目录下的文件,这个时候可以用subpath。

二、使用

  请注意,在使用subPath时,确保存储卷的内容与指定的子路径匹配,否则Pod可能会启动失败或出现其他问题。
  使用subPath指令,当挂载的卷(volumes)存在subPath(文件或目录),则卷不会自动创建subPath(目录);当卷(volumes)存在subPath(文件)是实现挂载文件的关键,否则就是挂载目录。

1、基础使用

下面是一个示例,演示如何使用subPath字段将PVC的特定子目录挂载到Pod中:
	apiVersion: v1  
	kind: PersistentVolumeClaim  
	metadata:  
	  name: my-pvc  
	spec:  
	  storageClassName: ""  
	  accessModes:  
	    - ReadWriteOnce  
	  resources:  
	    requests:  
	      storage: 1Gi
创建一个Pod(假设名称为my-pod),并将my-pvc下的test目录挂载到Pod的/app/data目录下:
	apiVersion: v1  
	kind: Pod  
	metadata:  
	  name: my-pod  
	spec:  
	  containers:  
	    - name: my-container  
	      image: my-image  
	      volumeMounts:  
	        - name: my-volume  
	          mountPath: /app/data  
	          subPath: test  # 子路径  
	  volumes:  
	    - name: my-volume  
	      persistentVolumeClaim:  
	        claimName: my-pvc

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

2、使用带有扩展环境变量的 subPath

  使用 subPathExpr 字段可以基于 downward API 环境变量来构造 subPath 目录名。 subPath 和 subPathExpr 属性是互斥的。

	apiVersion: v1
	kind: Pod
	metadata:
	  name: pod1
	spec:
	  containers:
	  - name: container1
	    env:
	    - name: POD_NAME
	      valueFrom:
	        fieldRef:
	          apiVersion: v1
	          fieldPath: metadata.name
	    image: busybox:1.28
	    command: [ "sh", "-c", "while [ true ]; do echo 'Hello'; sleep 10; done | tee -a /logs/hello.txt" ]
	    volumeMounts:
	    - name: workdir1
	      mountPath: /logs
	      # 包裹变量名的是小括号,而不是大括号
	      subPathExpr: $(POD_NAME)
	  restartPolicy: Never
	  volumes:
	  - name: workdir1
	    hostPath:
	      path: /var/log/pods

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

总结

  以上就是在K8S中subPath的基础使用,在部分场景中,我们可以通过使用subPath实现deployment应用挂载在持久存储中。有问题欢迎留言指导。