Volume
是kubernetes Pod
中多个容器访问的共享目录
Kubernetes
提供了众多的volume
类型,包括:emptyDir、hostPath、NFS、GlusterFS、configMap、Cephfs
1.emptyDir
emptyDir
类型的vloume
在Pod
分配到node
上时被创建,kubernetes
会在node
上自动分配一个目录,所以无须指定宿主机node
上对应的目录文件,该目录初始化内容为空,当Pod
从node
上被移除时,emptyDir
中的数据会被永久删除
①编辑emptyDir.yaml文件
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: web-demo-empty
spec:
replicas: 2
selector:
matchLabels:
app: app-demo-empty
template:
metadata:
labels:
app: app-demo-empty
spec:
containers:
- name: tomcat-demo
image: tomcat
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
volumeMounts:
# 将/mydata-data目录挂载到共享仓库
- mountPath: /mydata-data
name: datavol
- name: nginx-demo
image: nginx
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
volumeMounts:
# 将/mydata-data目录挂载到共享仓库
- mountPath: /mydata-data
name: datavol
# emptyDir是一个共享仓库(中央仓库)
volumes:
- name: datavol
emptyDir: {}
②执行kubectl create
$ kubectl create -f emptyDir.yaml
deployment.extensions/web-demo-empty created
③先进入tomcat-demo容器中创建文件
$ kubectl exec -it web-demo-empty-9b5644c45-7bpn5 -c tomcat-demo bash
$ touch /mydata-data/data.txt
$ ls /mydata-data/
data.txt
④在进入nginx-demo容器查看是否存在data.txt文件
$ kubectl exec -it web-demo-empty-9b5644c45-7bpn5 -c nginx-demo bash
$ ls /mydata-data/
data.txt
结论:经过试验证明emptyDir是一个共享空目录,可以让Pod中的多个容器之间共享该目录
2.hostPath
hostPath
类型的vloume
为Pod
挂载到宿主机上的目录或文件,使得容器可以使用宿主机的文件系统进行存储,但是在kubernetes
中,Pod
都是基于schedule
组件来动态调度在不同的node节点上,当一个Pod
在当前node节点上启动并通过hostPath
存储了文件到本地后,下次在调度另外一个节点上启动时,就无法使用之前节点上存储的文件了。
①编辑hostPath.yaml文件
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: web-demo-hostpath
spec:
replicas: 2
selector:
matchLabels:
app: app-demo-hostpath
template:
metadata:
labels:
app: app-demo-hostpath
spec:
containers:
containers:
- name: nginx-demo
image: nginx
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
volumeMounts:
- mountPath: /mydata-data
name: datavol
volumes:
- name: datavol
hostPath:
path: "/data"
②执行kubectl create
$ kubectl create -f hostPath.yaml
deployment.extensions/web-demo-hostpath created
③需要在每个node节点创建/data目录,并创建测试文件
$ mkdir /data
$ touch /data/test.txt
④进入容器里查看是否将/mydata-data挂载到了宿主机上
$ kubectl exec -it web-demo-hostpath-7866c644c4-7f8fk bash
$ ls /mydata-data/
test.txt