Kubernetes集群中,如果没有存储,所有pod中应用产生的数据都是临时的,pod挂掉,被rc重新拉起之后,以前产生的数据就丢掉了,这对有些场景是不可接受的,此时,外部存储就显得尤为重要。
这里重点介绍两个API资源
PersistentVolume(PV):集群中的一块网络存储,是集群中的资源,可类比集群中的Node资源;
PersistentVolumeClaim(PVC) : 用户对存储的需求,可类比pod,pod消费node资源,PVC就消费PV资源。
当然还有StorageClass等概念,这里不做详细说明(稳定后,后期文章专门介绍)。K8s存储管理主要分布在两个组件中(这里不包括api):kube-controller-manager和 kubelet。由于涉及的点比较多,我们分成几篇文章来介绍,本篇主要分析PersistentVolume。
代码基于社区,commit id: 65ddace3ed8e7c25546d12912c8dfdcd06ffe1e0
用例
Kubernetes支持的外部存储非常的多,如:AWSElasticBlockStore,AzureFile,AzureDisk,CephFS,Cinder,FlexVolume,GCEPersistentDisk,Glusterfs,HostPath,iSCSI,NFS,RBD,VsphereVolume等。
以HostPath存储的方式,举例说明:
创建PV(hostpath方式存储,目录 /tmp/data)
Yaml文件:
kind: PersistentVolume
apiVersion: v1
metadata:
name: task-pv-volume
labels:
type: local
spec:
capacity:
storage: 10Gi
accessModes:
ReadWriteOnce
hostPath:
path: “/tmp/data”
创建命令:
kubectl create -f http://k8s.io/docs/tasks/configure-pod-container/task-pv-volume.yaml
persistentvolume “task-pv-volume” created
查看结果:
kubectl get pv task-pv-volume
NAME CAPACITY ACCESSMODES RECLAIMPOLICY STATUS CLAIM REASON AGE
task-pv-volume 10Gi RWO Retain Available 17s
创建PVC
Yaml文件:
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: task-pv-claim
spec:
accessModes:
ReadWriteOnce
resources:
requests:
storage: 3Gi
创建命令:
kubectl create -f http://k8s.io/docs/tasks/configure-pod-container/task-pv-claim.yaml
persistentvolumeclaim “task-pv-claim” created
查看结果:(已经绑定上面创建的PV)
kubectl get pvc task-pv-claim
NAME STATUS VOLUME CAPACITY ACCESSMODES AGE
task-pv-claim Bound task-pv-volume 10Gi RWO 5s
PVC配置中没有指定volume name,PVController会从所有的volume中,找到合适的,和PVC进行绑定。
再查看上面创建的PV:
kubectl get pv tasck-pv-cvolume
NAME CAPACITY ACCESSMODES RECLAIMPOLICY STATUS CLAIM REASON AGE
task-pv-volume 10Gi RWO Retain Bound default/task-pv-claim 8m
创建Pod,使用上面创建的PV:
Yaml文件:
kind: Pod
apiVersion: v1
metadata:
name: task-pv-pod
spec:
volumes:
name: task-pv-storage
persistentVolumeClaim:
claimName: task-pv-claim
containers:
name: task-pv-container
image: nginx
ports:
containerPort: 80
name: “http-server”
volumeMounts:
mountPath: “/usr/share/nginx/html”
name: task-pv-storage
注:pod和PVC要在同一个namespace中。
创建命令:
kubectl create -f http://k8s.io/docs/tasks/configure-pod-container/task-pv-pod.yaml
pod “task-pv-pod” created
查看pod:
kubectl get pod task-pv-pod
NAME READY STATUS RESTARTS AGE
task-pv-pod 0/1 ContainerCreating 0 19s
kubectl get pod task-pv-pod
NAME READY STATUS RESTARTS AGE
task-pv-pod 1/1 Running 0 1m
进入pod,创建文件:
kubectl exec -it task-pv-pod /bin/bash
root@task-pv-pod:~# cd /usr/share/nginx/html/
root@task-pv-pod:/usr/share/nginx/html# echo “hello world”
Tag标签: