Kubernetes 之硬盘持久化和 EmptyDir 与 HostPath 挂载类型
持久化存储的意义
在 Kubernetes 中部署的应用都是以 Pod 的方式运行的。大部分情况这些 Pod 是无状态的。但是假如我们部署数据库或者需要一个存放关键文件的文件夹的时候,这时候我们就需要存储持久化以防止数据丢失。因为 Pod 是有生命周期的,如果 Pod 不挂载数据卷,那 Pod 被删除后这些数据会随之消失,对整个项目造成严重影响。它通常有emptyDir
、hostPath
和nfs
三种挂在模式。
EmptyDir 定义与使用
EmptyDir 是 Pod 多容器之间共享的临时性沟通目录,它会随着 Pod 的删除而删除。它通常只是用来多容器共享数据之用。
apiVersion: v1
kind: Pod
metadata:
name: pod-empty-dir
namespace: default
spec:
containers:
- name: container-write-empty-dir
image: busybox
imagePullPolicy: IfNotPresent
command: ["/bin/sh"]
args: ["-c","sleep 3600"]
volumeMounts:
- mountPath: /write-test
name: test-volume
- name: container-read-empty-dir
image: busybox
imagePullPolicy: IfNotPresent
command: ["/bin/sh"]
args: ["-c","sleep 3600"]
volumeMounts:
- mountPath: /read-test
name: test-volume
volumes:
- name: test-volume
emptyDir:
sizeLimit: 500Mi
root@k8s-master1:~# kubectl exec pod-empty-dir -c container-write-empty-dir -it -- /bin/sh
/ # echo "hello world" > /write-test/test.txt
/ # exit
root@k8s-master1:~# kubectl exec pod-empty-dir -c container-read-empty-dir -it -- cat /read-test/test.txt
hello world
HostPath 定义与使用
HostPath 只是将 Pod 中容器的目录映射到其所在的工作节点上,Pod 被删除后,该目录依旧存在于工作节点上。但是当恢复Pod节点的时候,它不一定存在于原来的工作节点上,所以这种挂在方式很不常用。
apiVersion: v1
kind: Pod
metadata:
name: pod-host-path
namespace: default
spec:
containers:
- name: container-host-path
image: busybox
imagePullPolicy: IfNotPresent
command: ["/bin/sh"]
args: ["-c","sleep 3600"]
volumeMounts:
- mountPath: /test
name: test-volume
volumes:
- name: test-volume
hostPath:
path: /tmp/test-host-path
type: DirectoryOrCreate