Kubernetes 核心实战 - 存储介绍
1. Kubernetes 存储概念及其关系
在 Kubernetes 中,存储的几个核心概念及其关系如下:
- Volume: 在 Pod 内部使用的一块存储,生命周期与 Pod 一致。不同类型的 Volumes 提供不同的存储功能,例如
emptyDir
、hostPath
、configMap
等。 - Persistent Volume (PV): 由管理员在集群中创建的一块存储资源,独立于 Pod 的生命周期。PV 代表集群中实际的存储,可以是本地存储、NFS、云存储等。
- Persistent Volume Claim (PVC): 用户请求存储资源的方式,PVC 表示用户对存储的需求。PVC 可以绑定到符合要求的 PV 上,从而为 Pod 提供持久化存储。
- Storage Class: 定义存储卷的类型和特性,允许动态创建 PV。用户可以通过 PVC 请求特定 Storage Class 类型的存储。
这些概念的关系可以简单理解为:用户通过 PVC 请求存储资源,PVC 与符合要求的 PV 绑定,Pod 使用 PVC 中的存储资源。Storage Class 用于定义和管理不同类型的存储资源(华为云上面的云硬盘就是通过这种方式,特点是自动创建)。
2. 绑定过程
- Kubernetes 控制器: Kubernetes 中的控制器(如 persistentvolume-controller)会定期检查集群中的 PVC 和 PV。
- 匹配 PVC 和 PV: 控制器将 PVC 的请求与 PV 的属性进行匹配。它检查 PVC 所需的存储容量和访问模式是否与 PV 的定义相符。
- 绑定: 如果找到匹配的 PV,控制器会将 PVC 绑定到该 PV。绑定后,PVC 的状态将更新为 Bound,并且 PV 的状态也会变为 Bound。
- 更新状态: PVC 的状态从 Pending 转变为 Bound,而 PV 的状态也会变为 Bound,并且 PV 的 claimRef 字段将指向绑定的 PVC。
Kubernetes 核心实战 - 存储示例
Volume:
Volume 是在 Pod 内部使用的一块存储,生命周期与 Pod 一致。以下是几种常见 Volume 类型的示例:
-
emptyDir: Pod 生命周期内的数据存储,适用于临时数据存储。
apiVersion: v1 kind: Pod metadata: name: emptydir-pod spec: containers: - name: app image: busybox command: ["/bin/sh", "-c", "sleep 3600"] volumeMounts: - mountPath: "/data" name: temp-storage volumes: - name: temp-storage emptyDir: { }
-
hostPath: 使用宿主机文件系统上的目录或文件。
apiVersion: v1 kind: Pod metadata: name: hostpath-pod spec: containers: - name: app image: busybox command: ["/bin/sh", "-c", "sleep 3600"] volumeMounts: - mountPath: "/data" name: host-storage volumes: - name: host-storage hostPath: path: /mnt/data
-
configMap: 将 ConfigMap 中的数据挂载到 Pod 中,适用于配置数据存储。
apiVersion: v1 kind: Pod metadata: name: configmap-pod spec: containers: - name: app image: busybox command: ["/bin/sh", "-c", "sleep 3600"] volumeMounts: - mountPath: "/config" name: config-storage volumes: - name: config