此文档中的信息可能已过时

此文档的更新日期比原文晚,因此其中的信息可能已过时。如果能阅读英文,请查看英文版本以获取最新信息: Use an Image Volume With a Pod

Pod 使用镜像卷

特性状态: Kubernetes v1.36 (GA; (默认启用))
More information about this feature

This is a stable feature in Kubernetes, and has been since version 1.36. It was first available in the v1.31 release.

本页展示了如何使用镜像卷配置 Pod。此特性允许你在容器内挂载来自 OCI 镜像仓库的内容。

准备开始

你必须拥有一个 Kubernetes 的集群,且必须配置 kubectl 命令行工具让其与你的集群通信。 建议运行本教程的集群至少有两个节点,且这两个节点不能作为控制平面主机。 如果你还没有集群,你可以通过 Minikube 构建一个你自己的集群,或者你可以使用下面的 Kubernetes 练习环境之一:

你的 Kubernetes 服务器版本必须不低于版本 v1.31.

要获知版本信息,请输入 kubectl version.

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

运行使用镜像卷的 Pod

为 Pod 启用镜像卷的方式是:在 .spec 中将 volumes[*].image 字段设置为一个有效的镜像并在容器的 volumeMounts 中消费此镜像。例如:

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
    
  1. 挂接到容器:

    kubectl exec image-volume -it -- bash
    
  1. 查看卷中某个文件的内容:

    cat /volume/dir/file
    

    输出类似于:

    1
    

    你还可以查看不同路径中的另一个文件:

    cat /volume/file
    

    输出类似于:

    2
    

进一步阅读

使用 subPath(或 subPathExpr

从 Kubernetes v1.33 开始,使用 image 卷特性时,可以利用 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
    
  1. 挂接到容器:

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

    cat /volume/file
    

输出类似于:

1

最后修改 January 04, 2026 at 3:29 PM PST: sync image-volumes custom-resource-definitions (fc6294ea47)