在 Pod 中使用镜像卷

特性状态: Kubernetes v1.36 [稳定] (默认启用)

本页面展示了如何配置使用镜像卷的 Pod。这允许你在容器内挂载 OCI 镜像仓库中的内容。

开始之前

你需要有一个 Kubernetes 集群,并且必须配置 kubectl 命令行工具以与你的集群通信。建议在至少有两个节点的集群上运行本教程,且这些节点不能作为控制平面主机。如果你还没有集群,可以通过 minikube 创建一个,或者使用以下 Kubernetes 演练场之一。

你的 Kubernetes 服务器版本必须在 v1.31 或更高版本。

要检查版本,请输入 kubectl version

  • 容器运行时需要支持镜像卷特性
  • 你需要能够在宿主机上执行命令
  • 你需要能够执行 exec 进入 Pod

运行使用镜像卷的 Pod

通过设置 .spec 中的 volumes[*].image 字段为有效的引用,并在容器的 volumeMounts 中使用它,即可为 Pod 启用镜像卷。例如:

apiVersion: v1
kind: Pod
metadata:
  name: image-volume
spec:
  containers:
  - name: shell
    command: ["sleep", "infinity"]
    image: debian
    volumeMounts:
    - name: volume
      mountPath: /volume
  volumes:
  - name: volume
    image:
      reference: quay.io/crio/artifact:v2
      pullPolicy: IfNotPresent
  1. 在你的集群上创建 Pod

    kubectl apply -f https://k8s.io/examples/pods/image-volumes.yaml
    
  2. 连接到容器

    kubectl exec image-volume -it -- bash
    
  3. 检查卷中文件的内容

    cat /volume/dir/file
    

    输出类似于

    1
    

    你也可以检查不同路径下的其他文件

    cat /volume/file
    

    输出类似于

    2
    

使用 subPath(或 subPathExpr

从 Kubernetes v1.33 开始,使用镜像卷特性时,可以使用 subPathsubPathExpr

apiVersion: v1
kind: Pod
metadata:
  name: image-volume
spec:
  containers:
  - name: shell
    command: ["sleep", "infinity"]
    image: debian
    volumeMounts:
    - name: volume
      mountPath: /volume
      subPath: dir
  volumes:
  - name: volume
    image:
      reference: quay.io/crio/artifact:v2
      pullPolicy: IfNotPresent
  1. 在你的集群上创建 Pod

    kubectl apply -f https://k8s.io/examples/pods/image-volumes-subpath.yaml
    
  2. 连接到容器

    kubectl exec image-volume -it -- bash
    
  3. 检查卷中 dir 子路径下的文件内容

    cat /volume/file
    

    输出类似于

    1
    

进一步阅读


上次修改时间:2026年2月3日 上午9:50 (PST):更新 ImageVolume 的 GA 文档 (711635430c)