首页 > 解决方案 > Kubernetes 持久卷

问题描述

任何人都可以澄清 Kubernetes 中的持久卷吗?

在下面的示例中,/my-test-project 位于持久卷中。那么,为什么我需要这些挂载,因为从技术上讲,我的整个目录 /my-test-project 是持久的?如果保留整个目录,这些挂载路径和子路径将如何提供帮助。谢谢!

volumeMounts:
    - name: empty-dir-volume
      mountPath: /my-test-project/data-cache
      subPath: data-cache
    - name: empty-dir-volume
      mountPath:  /my-test-project/user-cache
      subPath: user-cache

  volumes:
  - name: empty-dir-volume
    emptyDir: {}

标签: kuberneteskubernetes-pod

解决方案


您的/my-test-project整个目录不会被持久化

  • /my-test-project/data-cache主机中的mountPath 或路径保留empty-dir-volume在路径中data-cache

  • mountPath 保留/my-test-project/user-cacheempty-dir-volume路径中user-cache

这意味着当您/my-test-project/data-cachedata-cache. 对于用户缓存也是如此。每当您在其中创建文件时,/my-test-project/它都不会被持久化。假设您创建/my-test-project/new-dir,现在new-dir不会被持久化。

为了更好地解释,让我们看下面的例子(两个容器共享卷,但在不同的 mounthPath中):

apiVersion: v1
kind: Pod
metadata:
  name: share-empty-dir
spec:
  containers:
  - name: container-1
    image: alpine
    command:
      - "bin/sh"
      - "-c"
      - "sleep 10000"
    volumeMounts:
    - name: empty-dir-volume
      mountPath: /my-test-project/data-cache
      subPath: data-cache-subpath
    - name: empty-dir-volume
      mountPath:  /my-test-project/user-cache
      subPath: user-cache-subpath
  - name: container-2
    image: alpine
    command:
      - "bin/sh"
      - "-c"
      - "sleep 10000"
    volumeMounts:
      - name: empty-dir-volume
        mountPath: /tmp/container-2
  volumes:
  - name: empty-dir-volume
    emptyDir: {}

在容器 1 中:

  • mountPath 保留/my-test-project/user-cacheempty-dir-volume路径中user-cache-subpath
  • mountPath 保留/my-test-project/data-cacheempty-dir-volume路径中data-cache-subpath

在容器 2 中:

  • mountPath/tmp/container-2保存empty-dir-volume在路径“”中(表示“/”)

观察:

  • 触摸/my-test-project/user-cache/a.txt。我们可以在 container-2 中看到这个文件,/tmp/container-2/user-cache-subpath/a.txt并且反向将起作用
  • 触摸/my-test-project/data-cache/b.txt。我们可以在 container-2 中看到这个文件,/tmp/container-2/data-cache-subpath/a.txt并且反向将起作用
  • touch /tmp/container-2/new.txt,我们永远不能将 container-1 中的这个文件作为我们在 container-1 中指定子路径的基本路径
  • 类似地玩耍以获得更好的理解

注意:为了清楚起见,您使用的是emptyDirvolume 类型,这意味着每当 pod 被删除时,数据都会丢失。此类型仅用于在容器之间共享数据。


推荐阅读