Volume
在 Kubernetes 中,Pod 的存储通常通过 Volume 对象来管理。Volume 提供了一种在 Pod 生命周期内持久化数据的机制,并且可以跨容器共享。以下是对 Kubernetes Volume 的详细介绍,包括各种 Volume 类型和它们的用途:
1.Volume 基本概念
- Volume:Kubernetes Volume 是一种在 Pod 中共享和持久化数据的机制。它可以被 Pod 内的一个或多个容器使用。Volume 绑定在 Pod 上,在 Pod 生命周期内存在。
- Pod 生命周期与 Volume:Volume 的数据在 Pod 生命周期内保持持久。如果 Pod 被删除或重新调度到不同的节点,Volume 的数据仍然保留,除非指定的 Volume 类型与 Pod 生命周期绑定(如
emptyDir
)。
2.常见的 Volume 类型
1.emptyDir
-
用途:临时存储,当 Pod 创建时,
emptyDir
被创建,当 Pod 删除时,数据也会被删除。 -
特性:用于存储临时数据,例如缓存、临时文件等。
-
示例
apiVersion: v1 kind: Pod metadata: name: pod-empty-dir # 更新为符合命名规则的名称 spec: containers: - name: empty-dir-container # 更新为符合命名规则的名称 image: harbor.hiuiu.com/nginx/nginx:1.21.5 command: ["sh", "-c", "echo 'Hello, World!' > /data/hello.txt && sleep 3600"] volumeMounts: - mountPath: /cache name: cache-volume volumes: - name: cache-volume emptyDir: { } kubectl apply -f emptyDir.yaml kubectl get pod pod-empty-dir -o yaml | grep uid kubectl get pod -o wide #查看pod在哪个node节点上 cd /var/lib/kubelet/pods/cd93d19a-62aa-46e6-8c9b-ca22bed70927/volumes/kubernetes.io~empty-dir/cache-volume #在node节点上操作 touch 123 touch 456 kubectl exec -it pod-empty-dir -- /bin/bash cd /cache ls
2.hostPath
-
用途:将主机文件系统中的文件或目录挂载到 Pod 中。
-
特性:适用于单节点部署,不建议用于生产环境,因为它不具备高可用性。
-
示例
apiVersion: v1 kind: Pod metadata: name: pod-host-dir labels: app: pod-host-dir spec: containers: - name: host-dir-container image: harbor.hiuiu.com/nginx/nginx:1.21.5 volumeMounts: - mountPath: /usr/share/nginx/html name: nginx-volume volumes: - name: nginx-volume hostPath: path: /data/webs type: DirectoryOrCreate --- apiVersion: v1 kind: Service metadata: name: nginx-nodeport spec: type: NodePort selector: app: pod-host-dir ports: - port: 80 targetPort: 80 nodePort: 30007 --- kubectl apply -f hostPash.yaml kubectl apply -f service.yaml kubectl get pod -o wide #查看pod在哪个node节点上 cd /data/webs #节点操作 echo hello > index.html #主上登录 kubectl exec -it pod-host-dir -- /bin/bash cd /usr/share/nginx/html/ ls #真机访问 192.168.240.12:30007
将容器中多个目录挂载到真机上
apiVersion: v1
kind: Pod
metadata:
name: pod-host-dir
labels:
app: pod-host-dir
spec:
containers:
- name: host-dir-container