在 Kubernetes 中,卷提供了一种管理容器持久存储的方法。短暂存储会在 pod 终止时丢失,而卷与之不同,卷允许数据在单个容器的生命周期之外持续存在,从而使有状态的应用程序能正常运行。
下面的代码片段展示了如何在 Kubernetes 中定义持久卷 (PV) 和持久卷声明 (PVC),然后由 pod 使用。
[代码清单]
# Define a Persistent Volume
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 5Gi
accessModes:
- ReadWriteOnce
hostPath:
path: /mnt/data # Path on the host where data will be stored
# Define a Persistent Volume Claim
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
To create the PV and PVC, save the above YAML to a file named storage.yaml and run:
kubectl apply -f storage.
To use the PVC in a pod, you can define it as follows:
apiVersion: v1
kind: Pod
metadata:
name: my-stateful-pod
spec:
containers:
- name: my-stateful-container
image: my-image
volumeMounts:
- mountPath: /data
name: my-storage
volumes:
- name: my-storage
persistentVolumeClaim:
claimName: my-pvc
[执行结果]
持久卷 my-pv 和持久卷声称 my-pvc 将创建成功,pod 将以挂载在 `/data` 的指定卷启动。
持久卷(PV)是一种集群资源,代表集群中的一块存储空间,而持久卷申请(PVC)则是对这些资源的请求。当 PVC 绑定到 PV 时,就允许 pod 使用该存储。Kubernetes 支持各种类型的存储后端,包括云存储解决方案和本地磁盘。了解如何管理存储对于部署数据库等有状态应用至关重要。
[小知识]
hostPath 卷类型主要用于开发和测试,因为它将 pod 与特定节点绑定。
其他卷类型包括 NFS、AWS EBS 和 GCE Persistent Disks,可为生产环境提供更强大的解决方案。
必须考虑卷的访问模式,如 ReadWriteOnce、ReadOnlyMany 和 ReadWriteMany,因为它们决定了有多少 pod 可以同时访问卷。