概念
类似于Docker的数据卷挂载,将Pod中重要的文件挂载到宿主机上,如果Pod发生崩溃等情况自愈时,保证之前存储的数据没有丢失。
如上图中,将各个Pod中的目录挂载到存储层,如果Pod宕机后自愈均从存储层获取之前的数据,保证数据不会丢失。
网络文件系统-NFS
Master节点搭建一个NFS-Server,Node节点搭建NFS-Client,任意一个节点发生数据变化,均会同步给其他节点,即双向同步。
搭建
所有节点安装nfs-utils
shell
yum install -y nfs-utils
Master节点配置NFS-Server
shell
#nfs主节点
echo "/nfs/data/ *(insecure,rw,sync,no_root_squash)" > /etc/exports
mkdir -p /nfs/data
systemctl enable rpcbind --now
systemctl enable nfs-server --now
#配置生效
exportfs -r
Node节点配置映射文件
shell
# 测试是否映射成功
showmount -e ${换成自己Master节点的IP:192.168.65.130}
#执行以下命令挂载 nfs 服务器上的共享目录到本机路径 /root/nfsmount
mkdir -p /nfs/data
mount -t nfs ${换成自己Master节点的IP:192.168.65.130}:/nfs/data /nfs/data
# 写入一个测试文件
echo "hello nfs server" > /nfs/data/test.txt
验证
原生方式数据挂载
需要提前在nfs/data/
目录下创建nginx-pv目录
使用以下文件创建一个Deployment,同时挂载到nginx-pv目录下,进行验证:
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: nginx-pv-demo
name: nginx-pv-demo
spec:
replicas: 2
selector:
matchLabels:
app: nginx-pv-demo
template:
metadata:
labels:
app: nginx-pv-demo
spec:
containers:
- image: nginx
name: nginx
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
volumes:
- name: html
nfs:
server: 192.168.65.130
path: /nfs/data/nginx-pv
在Master/Node节点的nginx-pv目录下创建index.html,然后在pod中执行可以看到:
PV & PVC
PV:持久卷(Persistent Volume),将应用需要持久化的数据保存到指定位置
PVC:持久卷申明(Persistent Volume Claim),申明需要使用的持久卷规格
创建PV池
属于静态创建
shell
#nfs主节点
mkdir -p /nfs/data/01
mkdir -p /nfs/data/02
mkdir -p /nfs/data/03
创建PV
yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv01-10m
spec:
capacity:
storage: 10M
accessModes:
- ReadWriteMany
storageClassName: nfs
nfs:
path: /nfs/data/01
server: 192.168.65.130
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv02-1gi
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteMany
storageClassName: nfs
nfs:
path: /nfs/data/02
server: 192.168.65.130
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv03-3gi
spec:
capacity:
storage: 3Gi
accessModes:
- ReadWriteMany
storageClassName: nfs
nfs:
path: /nfs/data/03
server: 192.168.65.130
PVC的创建与绑定
其会根据storageClassName与需要的storage在静态PV池中获取符合需求的,然后进行自动绑定
yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: nginx-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 200Mi
storageClassName: nfs
创建Pod时绑定PVC
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: nginx-deploy-pvc
name: nginx-deploy-pvc
spec:
replicas: 2
selector:
matchLabels:
app: nginx-deploy-pvc
template:
metadata:
labels:
app: nginx-deploy-pvc
spec:
containers:
- image: nginx
name: nginx
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
volumes:
- name: html
persistentVolumeClaim:
claimName: nginx-pvc