Volume
容器销毁时,保存在容器内部文件系统中的数据会被清除,为了持久化保存容器数据,可以使用 Kubernetes Volum。
Volume 生命周期独立于容器, Pod 中容器可能销毁重建,但 Volume 会被保留。
emptyDir
一个 emptyDir Volume 是 Host 上的一个空目录。
emptyDir Volume 对容器是持久的。但 Pod 从节点删除时,Volume 的内容也会被删除。容器销毁而 Pod 还在,则 Volume 不受影响。
emptyDir Volume 的生命周期与 Pod 一致。
emptyDir 的用法有:
- 暂存空间,例如用于基于磁盘的合并排序
- 用作长时间计算崩溃恢复时的检查点
Web服务器容器提供数据时,保存内容管理器容器提取的文件
emptyDir-example.yaml1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21apiVersion: v1
kind: Pod
metadata:
name: test-pd
spec:
containers:
- image: nginx:1.7.9
name: test-container01
volumeMounts:
- mountPath: /cache
name: cache-volume
- name: test-container02
image: busybox:1.32.0
imagePullPolicy: IfNotPresent
command: ["/bin/sh","-c","sleep 3600"]
volumeMounts:
- mountPath: /test
name: cache-volume
volumes:
- name: cache-volume
emptyDir: {}
1 | [root@k8s01 ~]# kubectl apply -f emptyDir-example.yaml |
实际路径, pod 调度到了 k8s03 节点上。 文件位置如下
1 | [root@k8s01 ~]# kubectl get pod/test-pd -o yaml | grep uid |
hostPath
hostPath Volume 将 Docker Host 文件系统中已经存在的目录 mount 给 Pod 的容器。一般不会使用,因为增加了 Pod 与节点的耦合,限制了 Pod 的使用。不过 那些需要访问 k8s, Docker 内部数据的应用则需要使用 hostPath。
eg: kube-apisrver、kube-controller-manager等
kubectl edit --namespace=kube-system pod kube-apiserver-k8s-master 查看 kube-apiserver Pod 的配置。
Pod 销毁,hostPath 对应的目录还会保留。 但 Host 崩溃,hostPath 就无法访问了。
使用这种卷类型是请注意
- 因为:由于每个节点上的文件都不同,具有相同配置(例如从
podTemplate创建的)的pod在不同节点上的行为可能会有所不同 - 当
Kubernetes按照计划添加资源感知调度时,将无法考虑hostPath使用的资源 在底层主机上创建的文件或目录只能由
root写入。您需要在特权容器中以root身份运行进程,或修改主机上的文件权限以便写入hostPath卷
hostPath-example.yaml1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18apiVersion: v1
kind: Pod
metadata:
name: test-pd
spec:
containers:
- image: nginx:1.7.9
name: test-container
volumeMounts:
- mountPath: /test-pd
name: test-volume
volumes:
- name: test-volume
hostPath:
# directory location on host
path: /data
# this field is optional
type: Directory

1 | [root@k8s01 ~]# kubectl apply -f hostPath-example.yaml |
补
当一个 Pod 调度到一个节点上之后,kubelet 就要负责为这个 Pod 创建它的 Volume 目录。默认情况下,kubelet 为 Volume 创建的目录是如下所示的一个宿主机上的路径:
1 | /var/lib/kubelet/pods/<Pod的ID>/volumes/kubernetes.io~<Volume类型>/<Volume名字> |
接下来,kubelet 要做的操作就取决于 Volume 类型。
eg: 远程磁盘
attach: 将远程磁盘挂载到 pod 所在 node 节点上 (nfs 等不在远程的,可以直接执行第二步)(nodeName,即宿主机的名字。)mount: 格式化此磁盘,然后将它挂载到宿主机的指定挂载点 (dir,即 Volume 的宿主机目录)
1 | # 过程类似于: |