Longhorn部署完毕后会自动创建出StorageClass,我们只需要创建pvc即可,需要注意longhorn的pvc默认删除策略为delete,如果需要保留则需要手动将其StorageClass内的策略改为Retain。

创建pvc

1.编写pvc资源清单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root@k8s-master01:~/yaml/chapter05# vim pvc-dyn-longhon-demo.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-dyn-longhorn-demo
namespace: default
spec:
accessModes: ["ReadWriteOnce"]
volumeMode: Filesystem
resources:
requests:
storage: 2Gi
limits:
storage: 10Gi
storageClassName: longhorn

2.应用清单

1
2
3
4
5
6
root@k8s-master01:~/yaml/chapter05# kubectl  apply -f pvc-dyn-longhon-demo.yaml
persistentvolumeclaim/pvc-dyn-longhorn-demo created

root@k8s-master01:~/yaml/chapter05# kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
pvc-dyn-longhorn-demo Bound pvc-5db5bc10-5277-4452-bf3b-d821fa31cde1 2Gi RWO longhorn 2m10s

Pod中使用PVC

1.创建资源清单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
root@k8s-master01:~/yaml/chapter05# vim volume-pvc-longhorn-demo.yaml
apiVersion: v1
kind: Pod
metadata:
name: volumes-pvc-longhorn-demo
namespace: default
spec:
containers:
- name: redis
image: redis:alpine
imagePullPolicy: IfNotPresent
ports:
- containerPort: 6379
name: redisport
volumeMounts:
- name: redis-data-vol
mountPath: /data
volumes:
- name: redis-data-vol
persistentVolumeClaim:
claimName: pvc-dyn-longhorn-demo

2.应用配置清单

1
2
3
4
5
6
root@k8s-master01:~/yaml/chapter05# kubectl apply -f volumes-pvc-longhorn-demo.yaml
pod/volumes-pvc-longhorn-demo created

root@k8s-master01:~/yaml/chapter05# kubectl get pods
NAME READY STATUS RESTARTS AGE
volumes-pvc-longhorn-demo 1/1 Running 0 3m34s

3.查看挂载的卷

1
2
root@k8s-master01:~/yaml/chapter05# kubectl exec volumes-pvc-longhorn-demo -- mount | grep data
/dev/longhorn/pvc-5db5bc10-5277-4452-bf3b-d821fa31cde1 on /data type ext4 (rw,relatime)