k8s集群中持久化方式

1、hostpath方式

创建测试pod的yaml

apiVersion: v1
kind: Pod
metadata:
  name: test-hostpath
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: test-nginx
    volumeMounts:                               #挂载卷
    - mountPath: /test-nginx                    #挂载到容器内目录位置
      name: test-volume                         #卷名
  - image: tomcat:8.5-jre8-alpine
    name: test-tomcat
    imagePullPolicy: IfNotPresent
    volumeMounts:
    - mountPath: /test-tomcat
      name: test-volume
  volumes:
  - name: test-volume
    hostPath:
      path: /hostPath-data1                    #指定宿主机上的挂载目录,volume是和containers对齐,volumeMounts是在containers内声明
      type: DirectoryOrCreate                  #有data1目录则使用,无则在pod调度到的节点时自动创建

apply后

node01上查看目录

在该目录下创建文件

进入pod的容器查看test-nginx目录

容器内创建bb.text文件,宿主机查看

缺点:节点挂掉后,数据会丢失

2、nfs方式

安装nfs


#以k8s的控制节点作为NFS服务端
[root@master01 test]# yum install nfs-utils -y

#在宿主机创建NFS需要的共享目录
[root@master01 test]# mkdir /data/volumes -pv
mkdir: 已创建目录 '/data'
mkdir: 已创建目录 '/data/volumes'
[root@master01 test]# systemctl start nfs
[root@master01 test]# vim /etc/exports
/data/volumes 192.168.1.0/24(rw,no_root_squash)
#使NFS配置生效
[root@master01 test]# exportfs -arv
exportfs: /etc/exports [1]: Neither 'subtree_check' or 'no_subtree_check' specified for export "192.168.1.0/24:/data/volumes".
  Assuming default behaviour ('no_subtree_check').
  NOTE: this default has changed since nfs-utils version 1.0.x

exporting 192.168.1.0/24:/data/volumes
[root@master01 test]# service nfs start
重定向至 /bin/systemctl start nfs.service
[root@master01 test]# systemctl enable nfs
Created symlink /etc/systemd/system/multi-user.target.wants/nfs-server.service → /usr/lib/systemd/system/nfs-server.service.
[root@master01 test]# systemctl status nfs

其他节点也需要安装nfs

yum install nfs-utils -y
systemctl enable nfs

在master01的共享目录/data/volumes下创建index.html文件,内容为HelloWorld
创建nfs测试的yaml

[root@master02 test]# cat nfs.yaml 
apiVersion: v1
kind: Pod
metadata:
 name: test-nfs-volume
spec:
 containers:
 - name: test-nfs
   image: nginx
   imagePullPolicy: IfNotPresent
   ports:
   - containerPort: 80
     protocol: TCP
   volumeMounts:
   - name: nfs-volumes
     mountPath: /usr/share/nginx/html
 volumes:
 - name: nfs-volumes
   nfs:
    path: /data/volumes
    server: 我的机器ip
#注:path:  /data/volumes #nfs的共享目录
#server:我这里的是master01机器的ip,是安装nfs服务的地址

apply后

在容器内查看/usr/share/nginx/html路径下的文件

在容器内创建文件,宿主机共享目录下会直接同步


参考文章:https://blog.csdn.net/qq_39637333/article/details/130687918

posted @ 2024-05-28 16:56  白羽翎  阅读(73)  评论(0)    收藏  举报