唯一官方

数据持久化

Volume

  • kubernetes中的volume提供了在容器中挂载外部存储的能力
  • pod需要设置卷来源(spec.volume)和挂载点(spec.containers.volumeMounts)两个信息来使用对应的Volume

emptyDir

创建一个空卷,挂载到Pod中的容器。POD删除,该卷也会被删除

  • 应用场景: pod间数据的共享
$ vim  pod_emptydir.yml 
apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: write
    image: centos
    command: ["bash","-c","for i in {1..100};do echo $i >> /data/hello;sleep 1;done"]
    volumeMounts:
      - name: data
        mountPath: /data
  - name: read
    image: centos
    command: ["bash","-c","tail -f /data/hello"]
    volumeMounts:
      - name: data
        mountPath: /data
  volumes:
  - name: data
    emptyDir: {}
$ kubectl logs mypod -c read -f   #指定容器读
$ kubectl exec -it mypod -c read -- sh    #-c 进入指定的容器
$ kubectl get pod -o wide  #查看调度节点
$ cd /var/lib/kubelet/pods/   #进入调度节点的kubelet目录
$ docker ps | grep mypod      # 查看pod对应的数据目录
$ cd /var/lib/kubelet/pods/1e6cab01-c048-4bb2-ae47-fccf581741d4/volumes/kubernetes.io~empty-dir   #就可以看到对应的卷数据

hostPath

挂载node文件系统上的文件或者目录到Pod中的容器

  • 应用场景: pod中容器需要访问宿主机文件
$ vim vim pod_hostpath.yml
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: busybox
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 36000
    volumeMounts:
    - name: data
      mountPath: /data
  volumes:
  - name: data
    hostPath:
      path: /tmp
      type: Directory
$ kubectl apply -f pod_hostpath.yml
$ kubectl exec  my-pod  -- ls /data

NFS共享存储的使用

  • 环境准备
    • 准备一台nfs服务器(192.168.56.18),然后与k8s集群都安装nfs-utils
$ vim /etc/exports
/ifs/kubernetes *(rw,no_root_squash)
$ systemctl restart nfs
$ showmount -e
  • 挂载nfs到k8s集群
$ mount -t nfs 192.168.56.18:/ifs/kubernetes /mnt
  • 生成模板
$ kubectl create deploy web --image=nginx --dry-run -o yaml > deploy_nfs.yml
$ vim deploy_nfs.yml 
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: web
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web
  strategy: {}
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - image: nginx
        name: nginx
        resources: {}
        volumeMounts:
        - name: data
          mountPath: /usr/share/nginx/html
      volumes:
      - name: data
        nfs:
          server: 192.168.56.18
          path: /ifs/kubernetes
$ kubectl apply -f deploy_nfs.yml
$ kubectl get pod  && kubectl  exec -it web-xxxx bash
root@web-587c9fb4bd-9r7r4:/# cd /usr/share/nginx/html
root@web-587c9fb4bd-9r7r4:/usr/share/nginx/html# echo "aa" > index.html

$ kubectl scale deploy web --replicas=3   #扩容
$ kubectl expose deploy web --port=80 --target-port=80 --type=NodePort 

你可能感兴趣的:(唯一官方)