↓Skip to main content
  1. Docs/

containerd

·18 mins· ·
Owl Dawn
Author
Owl Dawn
Table of Contents

版本范围: 本文保留原有源码、图示和 Snapshotter 推导,运行时部分以 Linux、containerd Runtime v2 和 runc 为主要背景。原文同时引用了 1.7 与 2.0;下文涉及具体调用和配置时注明版本,不将某一实现当作所有运行时的统一行为。

容器
#

容器是一种特殊的进程,通过 namespace 和 cgroup 进行资源的隔离和限制。不同类型的 namespace 分别隔离进程、网络和挂载等视图,容器也可以按配置共享其中一部分;并非所有资源都由 namespace 隔离。

Mount Namespace
#

本节图示用于解释文件系统层次。图中的固定“五层”和 Init 层不是 OCI/containerd 的统一要求;Kubernetes 的 /etc/hosts、/etc/resolv.conf 等通常由运行时根据配置单独准备或挂载。

Linux 提供了 chroot 命令,可以改变进程的根目录,如执行 chroot /tmp/rootfs /bin/ls,命令进程的根目录变为了 /tmp/rootfs,因此 ls 命令的输出就是 /tmp/rootfs 中的内容。

rootfs(根文件系统),挂载在容器的根目录,用于给容器进程提供隔离后执行环境的文件系统。

  • rootfs 包含应用所需的用户空间文件和目录,不包含独立运行的宿主机内核,使得应用以及它运行所需的依赖都被封装在了一起

  • 引入层(layer) 的概念,即会改变文件系统的构建步骤通常产生新的文件系统层,单纯修改镜像元数据的步骤不一定产生层(联合文件系统,联合挂载)

    第一层:只读层。即容器 rootfs 最下面得五层

    第二层:可读写层。最上面的一层。在没有写入文件之前,这个目录是空的。一旦在容器里做了写操作,修改产生的内容就会以增量的方式出现在这个层中。删除操作则创建一个 whiteout 文件将只读层中的文件遮挡住

    第三层:Init 层。这是图中旧 Docker/AUFS 实现的概念,用来存放 /etc/hosts、/etc/resolv.conf 等信息(启动容器是需要写入一些用户指定的值,如 hostname,这些修改往往只对当前容器有效,commit 时不需要连同连同读写层一起提交掉)

bind mount 可以把已有文件或目录暴露在另一个挂载位置,例如 mount --bind /path1 /path2。两个位置访问的是同一底层内容,不是简单把一个 dentry 改指向另一个 inode。rootfs 可以来自 bind、overlay 等挂载方式,并不固定只用 bind mount。

Mount namespace 隔离挂载视图,单独创建它不会自动切换根目录;初始挂载信息通常从原视图继承。运行时还要准备挂载、处理传播属性并切换根目录,常见手段包含 pivot_root 或相应的 chroot 流程。chroot 只改变路径解析的根,不是完整的安全隔离机制。

Containerd
#

Containerd 是一个高度模块化的容器运行时,启动后,主进程会在 grpc server 下注册一系列的 grpc service,如 CRIService、TasksService 等

Containerd 的具体功能基本都是通过调用这些 gRPC service 完成的,启动后会启动一个 gRPC server,默认监听位置为 /run/containerd/containerd.sock

CRI Service
#

在 Kubernetes 中,在 node 上,kubelet 通过 CRI 调用 containerd 来创建 sandbox(pod)、container 等,而 Containerd 提供了 CRI GRPC 接口供 kubelet 使用。而对于 docker 原生项目,Containerd 提供了原生的 Grpc 接口。

Runtime
#

containerd 负责管理和协调容器创建、启动、退出及删除,但不直接完成所有底层隔离操作。 常见 Runtime v2 路径是 containerd → shim → runc;runc 按 OCI Runtime Spec 配置 rootfs、namespace、cgroup 等并创建或启动进程。

创建容器的顺序为:

  1. containerd daemon 接收来自 client 的创建 container 的请求(可能是 kubelet 通过 cri 发起的,或者 ctr、nerdctl 这些 client 发起的)
  2. containerd daemon 准备容器所需的 rootfs 和 container 配置信息(OCI runtime config)
  3. containerd 通过 Runtime v2 接口启动或连接 shim,并向其提供 bundle、挂载和运行配置等信息;不是把整个 rootfs 文件内容复制到一个运行时请求中。
  4. 在常见 runc v2 实现中,shim 暴露 ttRPC socket,再按请求调用 runc 创建或启动容器;不是由 runc 在创建容器后再启动 shim。
  5. containerd 获取 shim 公告的连接信息,随后通过相应接口管理任务和接收状态。启动握手格式随版本变化,不能把 stdout 永远只看作一个裸 socket 字符串。

在具体实现中 containerd 的 runtime 分为两个部分

  • runtime shim
    • shim 是与 containerd daemon 直接沟通的结构。是一个二进制文件,在 v1.7 版本中为 containerd-shim-runc-v2,containerd daemon 会直接调用这个二进制文件,创建一个 containerd shim 进程
  • runtime engine
    • 即我们常说的狭义上的容器运行时,如 runc。以二进制形式存在,runtime engine 是真正负责调用操作系统接口以创建、启动和删除容器的模块。在这条管理链路中通常由 shim 调用;runc 也可以作为独立命令行工具使用

containerd

图中 Runtime Shim 与 Runtime Engine 要分开读:shim 是持续管理任务的服务,runc 通常在完成相应命令后退出,并非每个容器旁都有一个始终运行的 runc 守护进程。CRI 插件与 Tasks 服务也不一定通过外部 socket 绕一圈,v2.0.0 内置 CRI 客户端使用了进程内服务连接。

Container、Task、Sandbox
#

名称 含义 是否等于正在运行的业务进程
Container 配置和元数据,例如镜像、OCI Spec、snapshot key、runtime 类型 否,记录可以先于进程存在
Task 容器的执行实例及其生命周期操作 与进程相关,但 Task 创建后还需要 Start 才开始执行容器程序
Pod Sandbox 承载 Pod 共享环境的运行时抽象,常见 Linux 实现包含 pause 容器 不是业务容器本身,其他 sandbox 实现也不一定使用 pause

因此,CreateContainer 返回成功,不表示应用已经启动;看到 Container 元数据也不表示 Task 一定还在运行。

创建 pod 流程
#

kubelet 依次调用 RunPodSandbox、CreateContainer、StartContainer 三个接口来创建 pod 中的容器。

RunPodSandbox
#

以下顺序对应普通非 hostNetwork Linux sandbox 的概念流程。hostNetwork 不需要为 Pod 创建独立网络命名空间;VM 类 sandbox 也可能有不同的准备顺序,具体查看对应 sandbox controller。

  1. kubelet 通过内置的 CRI client 调用 containerd 的 cri service 的 RunPodSandbox(gRPC call)
  2. cri service 根据 gRPC Request(RunPodSandboxRequest)中描述创建 SandboxInfo,存储到本地的 metadata 数据库中(相关元数据由本地存储维护,containerd 常用 bbolt;具体记录还包括 CRI 内存状态与扩展信息)
  3. cri service 创建 network namespace,并调用 CNI 插件初始化 container network
  4. cri service 启动 sandbox,主要把 pause container 跑起来。这里启动 pause container 的步骤与后续启动业务 container 的步骤基本相同

CreateContainer
#

创建 Container 元数据、OCI 配置和可写 snapshot 等准备对象,此时通常还没有启动业务进程。不能说这一步没有创建任何容器对象。

  1. kubelet 通过其内置的 CRI Client 调用 containerd 的 cri service 的 CreateContainer(gRPC call)
  2. cri service 从 gRPC Request (CreateContainerRequest)的描述中,得到 sandbox id,并据此从 metadata 数据库中找到之前创建的 sandbox 对象
  3. cri service 根据 CreateContainerRequest 中的描述,创建并配置 Container 对象。其中重要的配置步骤包括
    1. 使用已准备的镜像 snapshots,并按 snapshotter 配置创建容器可写 rootfs;普通 CRI PullImage 流程通常已完成镜像下载与 unpack,不是每次 CreateContainer 都重新解压全部镜像
    2. 生成 oci runtime spec
  4. cri service 将 Container 对象写入到 metadata 数据库中

StartContainer
#

  1. kubelet 通过其内置的 CRI client 调用 containerd 的 cri service 的 StartContainer
  2. cri service 从 StartContainerRequest.container_id 取得目标 container,再根据已保存的容器信息找到所属 sandbox;这个请求不是直接携带 sandbox id。
  3. cri service 从 metadata 数据库中找到之前创建的 container 对象
  4. cri service 创建 Task 对象。一个运行态的 container 在 containerd 的内存中是使用 Task 对象来描述的。所以。创建实际运行的 container 的过程,其实就是创建并启动 Task 的过程。具体过程:
    1. cri service 通过 containerd 客户端的 Task 接口创建执行实例;在 v2.0.0 内置部署中可以连接进程内服务,不应固定描述为经 /run/containerd/containerd.sock 发起另一次外部 gRPC。
    2. TaskService 调用 PlatformRuntime(PlatformRuntime 是个接口,具体的实现是 TaskManager)创建 runtime.Task
    3. TaskManager 尝试启动一个 containerd shim 进程
      1. 如果当前要创建的 container(Task)属于某个已创建的 Sandbox(比如,创建业务 container 时,本质上是向之前已经创建了 pause container 的 sandbox 中添加 container,此时,已经存在当时创建 pause container 时创建的 shim 进程),那么不创建新的 shim 进程(常见 io.containerd.runc.v2 实现可根据 sandbox-id 等分组信息复用 shim;具体由 runtime handler、分组与配置决定,不是 CRI 对所有实现的保证)
      2. 否则,执行 containerd-shim-runc-v2 这个二进制,启动一个 shim 进程,该 shim 进程会启动一个 ttrpc service,并把其所监听的 unix socket 地址返回给 TaskManager
    4. TaskManager 通过 ttrpc 接口调用 shim 进程
    5. shim 调用 runc(或相应 runtime engine)创建容器进程,随后启动 Task,执行容器程序。

Snapshot
#

OCI 镜像格式分为多层(layer1、layer2、layer3…),而最终的文件系统内容基于每层的 merge 构建。我们假设每 merge 一层,就会生成一个 snapshot。

如果使用下文的 native snapshotter 这类复制实现,创建 $snapshot_2$ 时会先把 $snapshot_1$ 的内容复制到新目录,再 apply $layer_2$ 的差异。不是所有 snapshotter 都需要全量复制;这种实现会导致:

  1. 不必要的文件拷贝带来的耗时
  2. 文件反复拷贝带来的存储冗余。对于 $snapshot_1$ 中的内容要被存储 n 次

对于以上问题,有很多解决方法,比如使用 AUFS、overlayfs 这样的联合文件系统,或 btrfs、ZFS 等支持快照的文件系统,这样避免了 merge 时对上级 snapshot 的全量复制。而这些方式,都需要经过一个 “根据 layer 创建 snapshot” 的过程,这个过程针对上述的不同的方法有着不同的实现。

containerd 将这个行为抽象出来,成为了一个独立的组件,即 Snapshotter,就可以根据不同的场景,选择不同的 snapshotter 来创建和管理 snapshot,进而决定如何构建 rootfs。而用户也可以自定义这一接口,通过 gRPC 的封装,然后注册到 containerd 中使用。

Snapshotter
#

Snapshotter 接口定义:

type Snapshotter interface {
	// Stat returns the info for an active or committed snapshot by name or
	// key.
	//
	// Should be used for parent resolution, existence checks and to discern
	// the kind of snapshot.
	Stat(ctx context.Context, key string) (Info, error)

	// Update updates the info for a snapshot.
	//
	// Only mutable properties of a snapshot may be updated.
	Update(ctx context.Context, info Info, fieldpaths ...string) (Info, error)

	// Usage returns the resource usage of an active or committed snapshot
	// excluding the usage of parent snapshots.
	//
	// The running time of this call for active snapshots is dependent on
	// implementation, but may be proportional to the size of the resource.
	// Callers should take this into consideration. Implementations should
	// attempt to honor context cancellation and avoid taking locks when making
	// the calculation.
	Usage(ctx context.Context, key string) (Usage, error)

	// Mounts returns the mounts for the active snapshot transaction identified
	// by key. Can be called on a read-write or readonly transaction. This is
	// available only for active snapshots.
	//
	// This can be used to recover mounts after calling View or Prepare.
	Mounts(ctx context.Context, key string) ([]mount.Mount, error)

	// Prepare creates an active snapshot identified by key descending from the
	// provided parent.  The returned mounts can be used to mount the snapshot
	// to capture changes.
	//
	// If a parent is provided, after performing the mounts, the destination
	// will start with the content of the parent. The parent must be a
	// committed snapshot. Changes to the mounted destination will be captured
	// in relation to the parent. The default parent, "", is an empty
	// directory.
	//
	// The changes may be saved to a committed snapshot by calling Commit. When
	// one is done with the transaction, Remove should be called on the key.
	//
	// Multiple calls to Prepare or View with the same key should fail.
	Prepare(ctx context.Context, key, parent string, opts ...Opt) ([]mount.Mount, error)

	// View behaves identically to Prepare except the result may not be
	// committed back to the snapshot snapshotter. View returns a readonly view on
	// the parent, with the active snapshot being tracked by the given key.
	//
	// This method operates identically to Prepare, except the mounts returned
	// may have the readonly flag set. Any modifications to the underlying
	// filesystem will be ignored. Implementations may perform this in a more
	// efficient manner that differs from what would be attempted with
	// `Prepare`.
	//
	// Commit may not be called on the provided key and will return an error.
	// To collect the resources associated with key, Remove must be called with
	// key as the argument.
	View(ctx context.Context, key, parent string, opts ...Opt) ([]mount.Mount, error)

	// Commit captures the changes between key and its parent into a snapshot
	// identified by name.  The name can then be used with the snapshotter's other
	// methods to create subsequent snapshots.
	//
	// A committed snapshot will be created under name with the parent of the
	// active snapshot.
	//
	// After commit, the snapshot identified by key is removed.
	Commit(ctx context.Context, name, key string, opts ...Opt) error

	// Remove the committed or active snapshot by the provided key.
	//
	// All resources associated with the key will be removed.
	//
	// If the snapshot is a parent of another snapshot, its children must be
	// removed before proceeding.
	Remove(ctx context.Context, key string) error

	// Walk will call the provided function for each snapshot in the
	// snapshotter which match the provided filters. If no filters are
	// given all items will be walked.
	// Filters:
	//  name
	//  parent
	//  kind (active,view,committed)
	//  labels.(label)
	Walk(ctx context.Context, fn WalkFunc, filters ...string) error

	// Close releases the internal resources.
	//
	// Close is expected to be called on the end of the lifecycle of the snapshotter,
	// but not mandatory.
	//
	// Close returns nil when it is already closed.
	Close() error
}

其中,Prepare() 方法用于创建一个 active 状态的 snapshot,经过 mount 之后,调用 Commit 方法,将其转化为一个 committed 状态的 snapshot,此时 committed snapshot 可以作为后续 snapshot 的 parent。Prepare 返回挂载说明,并不保证已经替调用方执行了挂载;Commit 也不是应用文件内容的步骤,文件层应在它之前 apply 完成。

在 OCI 镜像格式中,对于镜像层,记其 diff id 分别为 $(diffid_1, diffid_2, diffid_3, …, diffid_n)$,那么 chain id 的计算方式如下: $$chain_id_1 = diff_id_1$$ $$chain_id_n = f_{digest}(f_{append}(chain_id_{n-1}, diff_id_n)) $$ 可以看到, $layer_n$ 的 chain id 是由 $(layer_1, layer_2, layer_3, …, layer_n)$ 共同决定的,即包含了所有的“祖先” layer。

上式的 append 要包含一个 ASCII 空格作为分隔:chainID_n = digest(chainID_(n-1) + " " + diffID_n)。DiffID 是未压缩 layer tar 内容的摘要;Registry manifest 中的 layer digest 则标识所引用 blob,压缩层通常不同于 DiffID。ChainID 用有序 DiffID 链标识层应用结果,不能只用最后一层的摘要代替。

构建过程
#

以 native snapshotter 为例

  • 处理 $layer1$
    • containerd 调用 Snapshotter 的 Prepare 方法 sn.Prepare(ctx, key, parent.String(), opts...) 通知snapshotter为 $snapshot_1$ “准备”一个工作目录。说明一下这个函数的参数:

      1. key 是个包含了当前了 $layer_1$ 的 chain id 的 $chain_id_1$ 的随机字符串
      2. parent.String() 是当前正在处理的 layer 的 parent layer 的 id,由于当前处理的是 $layer_1$,它没有 parent,所以这里的 parent.String() 是 ""
    • native snapshotter 接收到 Prepare 的通知后,发现传入的 parent 是空,于是准备一个全新的空白目录,并返回之。注意,这里返回的不是一个路径名字符串,而是一个 Mount 结构体数组。表示其中的 Mount 定义如下:

      // Mount is the lingua franca of containerd. A mount represents a
      // serialized mount syscall. Components either emit or consume mounts.
      type Mount struct {
      	// Type specifies the host-specific of the mount.
      	Type string
      	// Source specifies where to mount from. Depending on the host system, this
      	// can be a source path or device.
      	Source string
      	// Target specifies an optional subdirectory as a mountpoint. It assumes that
      	// the subdirectory exists in a parent mount.
      	Target string
      	// Options contains zero or more fstab-style mount options. Typically,
      	// these are platform specific.
      	Options []string
      }
      

      即 snapshotter 告诉 containerd 备好了一个目录 Source,你应该使用 Type 类型的挂载方式挂载到某个目录下面来用。同时,你挂载的具体位置,应该是 ${你自定义的目录}/Target,挂载的时候记得用我给你的 Options。

      比如,native snapshotter 接收到 Prepare 的通知后,准备了一个路径为 /path/snapshot/1 的空目录,那么它应该返回的 Mount 结构体数组大致是这样的:

      mounts := []Mount{
      	{
      		Type: "bind",
      		Source: "/path/snapshot/1",
      		Target: "",
      		Options: []string{"rbind", "rw"},
      	},
      }
      
    • 接着,containerd 拿到了 native snapshotter 返回的 mounts,然后尝试使用 mountpackage 下的 All(mounts, root) 方法,将 mounts 中的各个 Source 挂载到 root 下。 细节如下:

      1. containerd 创建临时目录,记为 root,我们假设其为 /path/to/tmp/root/1
      2. 遍历 mounts 数组,发现只有一个,去除这个唯一一个元素 mount
      3. 取出 mount 中的 target,将其拼接到 /path/to/tmp/root/1 后面,得到最终的挂载路径 finalTarget。由于 Target 是 "",所以 finalTarget 就是 /path/to/tmp/root/1
      4. containerd 调用 mount,根据 mount 中的 Type,将 mount 的 Source 挂载到 finalTarget 中。本例中,相当于执行了:mount --bind /path/snapshot/1 /path/to/tmp/root/1
    • 现在 containerd 知道 /path/to/tmp/root/1 就是 $snapshot_1$ 的工作目录。它将 $layer_1$ 拆包解压,并 apply 到 /path/to/tmp/root/1 中。 由于 /path/to/tmp/root/1 被挂载了一个空目录,所以这一步相当于把 $layer_1$ 拆包后的所有文件 copy 到 /path/to/tmp/root/1 中

    • containerd 调用 snapshotter 的 Commit 方法 sn.Commit(ctx, chainID.String(), key, opts...),通知 snapshotter ”提交“ 当前的 snapshot。 这一步时机是 containerd 通知 snapshotter 已经处理完成当前 snapshot,需要持久化它的信息到 metadata 数据库中,以备后续使用 这个函数的各参数:

      1. chainID.String() 是 containerd 希望 snapshotter 持久话这个 snapshot 时使用的 Name,后续 containerd 都将使用这个 Name 来索引这个 snapshot。这个例子中的值就是 $layer_1$ 的 chain\_id_1
      2. key 是最开始 containerd 调用 Prepare· 函数时给定的随机字符串,用以告诉 snapshotter 要持久化的是哪个 snapshot
  • 处理 $layer_2$
    • containerd 调用 Snapshotter 的 Prepare 方法 sn.Prepare(ctx, key, parent.String(), opts...),通知 snapshotter 为 $snapshot_2$ “准备”一个工作目录。此时函数参数:
      1. key 是个包含了当前了 $layer_2$ 的 chain id 的 $chain_id_2$ 的随机字符串($layer_1$ 和 $layer_2$ 的 diff id 总和哈希之后的结果)
      2. parent.String() 当前处理的是 $layer_2$,它的 parent 是 $layer_1$,所以这里的 parent.String() 是 $layer_1$ 的 chain\_id_1(即 Commit $snapshot_1$ 时使用的 Name
    • native snapshotter 接收到 Prepare 的通知,首先创建一个空白目录 dir2,根据传入的 Parent $chain_id_1$ 从 metadata 数据库中查到 $snapshot_1$ 的目录 dir1,接着将 dir1 中的内容 cpy 到 dir2 中,然后使用 dir2 作为 Source,和处理 $layer_1$ 时一样,组装 Mount 数据并返回 假设 dir2 是 /path/snapshot/2,与下文临时挂载点 /path/to/tmp/root/2 区分,那么返回的 Mount 数据大致是这样的:
      mounts := []Mount{
      	{
      		Type: "bind",
      		Source: "/path/snapshot/2",
      		Target: "",
      		Options: []string{"rbind", "rw"},
      	},
      }
      
    • containerd 拿到 native snapshotter 返回的 Mount,尝试使用 mount package 下的 All(mounts, root) 方法,将 mounts 中的各个 Source 挂载到 root 下。
      1. containerd 创建临时目录,记为 root,我们假设其为 /path/to/tmp/root/2
      2. 遍历 mounts 数组,发现只有一个,取出这个唯一一个元素 mount
      3. 取出 mount 中的 target,将其拼接到 /path/to/tmp/root/2 后面,得到最终的挂载路径 finalTarget。由于 Target 是 "",所以 finalTarget 就是 /path/to/tmp/root/2
      4. containerd 调用 mount,根据 mount 中的 Type,将 mount 的 Source 挂载到 finalTarget 中。本例中,相当于执行了:mount --bind /path/snapshot/2 /path/to/tmp/root/2
    • 现在 containerd 知道 /path/to/tmp/root/2 就是 $snapshot_2$ 的工作目录,且应用第二层之前,该路径展示的是从第一层复制而来的内容。它将 $layer_2$ 拆包解压,并 apply 到 /path/to/tmp/root/2 中。这样 /path/to/tmp/root/2 将是 $layer_1$ 和 $layer_2$ 的联合。
    • Commit
  • 处理 $layer_3$ 以及剩余所有的 $layer$。处理完成后,我们得到一个目录 $snapshot_n$,其中包含所有 layer 合并之后的内容,即当前镜像中的所有内容

overlay snapshotter
#

补充:这里说的 upperdir、lowerdir、workdir 和 merged 是 overlayfs 的不同角色。upperdir 保存当前可写变化,lowerdir 提供已有层,workdir 是内核工作目录,merged 是挂载后看到的合并视图。修改 lower 层中的文件时通常发生 copy-up,删除还涉及 whiteout/opaque 语义,不是真的删除共享只读层中的原文件。 native snapshotter 每层文件都会被来回 copy,有大量的运行时开销和存储空间占用。而 overlay snapshotter 则解决了这个问题

  • 在处理 $layer_1$ 是 overlay 和 native 基本没有区别
  • 当处理 $layer_2$ 时,overlay snapshotter 在创建了那个为 $snapshot_2$ 准备的临时目录后,overlay 不会将 $snapshot_1$ 中的文件都 copy 到这个临时目录中,而是直接返回 Mount 数组。数组中的唯一的 mount 元素告诉 containerd:使用 overlay 方式挂载,对于第二层,lowerdir 是第一层的目录,upperdir 是新准备的目录,还需要配置 workdir;层数更多时 lowerdir 会包含按优先级排列的父层目录。通过这样的命令,containerd 最终得到的 mergeddir 将会展现出 lowerdir(即 $snapshot_1$ 的目录)的样子,而 containerd 在后续 apply $layer_2$ 拆包后的文件时,对文件系统的更改会反应在 upperdir(即 $snapshot_2$)的目录中。
  • 后续 layer 处理相同

snapshot 到 rootfs
#

最终得到的 snapshot 是 $snapshot_n$,但是容器进程不能直接在 $snapshot_n$ 的目录进行读写,因为多个容器需要共享同一个镜像

containerd 的做法:创建容器时依次:

  • unpack 镜像,得到 $snapshot_n$
  • 调用 snapshotter 的 Prepare 方法,此时传入的 parent 是 $layer_n$ 的 chain id。
    • 如果是 native snapshotter,会创建一个新的目录,并将 parent,也就是 $snapshot_n$ 的目录中的所有文件都 copy 到这个新的目录中,然后返回一个 Source 就是这个新的目录 new_dir,Type 是 bind 的 Mount 结构。这样 containerd 可以直接将 new_dir mount 到 path/to/runtime/bundle/rootfs 上。容器进程实际是在 new_dir 上读写
    • 对于 overlay snapshotter,会创建一个新的目录,但是不做 copy 动作。而是创建一个新的目录 new_dir 之后直接返回一个 Mount 结构,这个 Mount 结构指明 lowerdir 是 $snapshot_1$ 到 $snapshot_n$ 的所有的目录,upperdir 是 new_dir,并且需要使用 overlay 类型 mount 到 path/to/runtime/bundle/rootfs 上。这样 /path/to/runtime/bundle/rootfs 作为 mergeddir,可以看到 $snapshot_1$ 到 $snapshot_n$ 的所有目录合并后的文件系统(即 image 的所有层合并后的结果),同时也是可写的。容器进程所有执行的对文件系统的更改都将反应在 upperdir 也就是 new_dir 中
  • 使用上述 mount 后的目录,即 /path/to/runtime/bundle/rootfs 作为 bundle 的 rootfs,并结合生成的 config 文件,调用 runc 以创建容器

镜像与存储管理
#

镜像下载与解包
#

阶段 保存或生成什么 作用
下载 Content Store 中的 manifest、config 和 layer blob 按内容摘要保存原始内容,不等于已得到可运行目录
Unpack Snapshotter 管理的镜像层快照 按顺序应用文件系统差异,例如新增、修改与删除
准备容器 rootfs 基于镜像最后一个 committed snapshot 的 active snapshot 多个容器共享镜像层,但各自有可写变化
创建和启动 Task shim 管理的执行实例 在准备好的环境中运行应用

镜像名/标签、blob digest、snapshot key 和 container ID 分别指不同对象,不应拿一个名称直接推断另一个存储目录。containerd 管理元数据,Content Store 保存字节,Snapshotter 管理可挂载文件系统,它们共同构成镜像到容器的链路。

常见非惰性拉取会先下载并解包相应内容;Nydus、stargz 等远程/惰性 snapshotter 则可能在运行中按需取数据,不能将全量下载前置当作所有方案的必然条件。Dragonfly 主要优化分发,snapshotter 决定 rootfs 如何提供,两者处于不同环节。

常用工具
#

工具 主要入口 适合做什么
ctr containerd 原生 API 低层调试插件、镜像、Container、Task 与 snapshot
crictl CRI 对照 kubelet 的 sandbox、容器、镜像视角排查
nerdctl containerd API 与相应上层功能 使用接近 Docker CLI 的方式运行和管理容器

Kubernetes 的 containerd 元数据通常位于 k8s.io namespace。它不是 Kubernetes namespace,也不是 Linux namespace,只是 containerd API 的资源组织方式,不是安全隔离边界。默认 ctr 看不到对象时,应先检查连接地址和 namespace,不要立即判断容器不存在。

# 在目标 Linux 节点上按实际权限执行,socket 路径按安装方式核对。
ctr --address /run/containerd/containerd.sock namespaces list
ctr --address /run/containerd/containerd.sock --namespace k8s.io containers list
ctr --address /run/containerd/containerd.sock --namespace k8s.io tasks list
ctr --address /run/containerd/containerd.sock plugins list

# 通过与 kubelet 一致的 CRI 入口查看;适用时另核对 image endpoint。
crictl --runtime-endpoint unix:///run/containerd/containerd.sock pods
crictl --runtime-endpoint unix:///run/containerd/containerd.sock ps -a

CRI Registry 配置不一定被 ctr/nerdctl 使用。尤其是镜像源和证书问题,不能用一次 ctr 拉取成功就断言 kubelet 的 CRI 路径正常;ctr 使用 hosts.toml 时需要按其参数显式选择 hosts 目录。

配置版本
#

以下仅为位置对照,不是替换整份配置的安装清单。containerd 2.0 引入配置格式 version 3,仍支持迁移 version 2;现有环境应先检查 containerd --version 和 containerd config dump 的有效结果。

功能 1.x 常见 version 2 配置位置 2.x version 3 配置位置
CRI 运行时设置 plugins."io.containerd.grpc.v1.cri".containerd plugins."io.containerd.cri.v1.runtime".containerd
CRI 镜像 snapshotter plugins."io.containerd.grpc.v1.cri".containerd.snapshotter plugins."io.containerd.cri.v1.images".snapshotter

在 systemd 管理节点上,应核对 kubelet 与运行时使用的 cgroup driver 是否协调一致;SystemdCgroup 的具体表位置也跟配置版本有关。修改主配置可能需要重启守护进程,应先安排影响范围;只更新生效目录下的 Registry hosts 文件通常可以动态读取,二者不要混为一谈。

资源清理与垃圾回收
#

业务进程退出后,Container 元数据和 snapshot 可能还在;清理 Task、删除 Container、释放可写 snapshot、回收镜像 blob 是不同动作。Leases 和资源引用帮助保护仍在使用的内容,删除镜像标签也不保证相关共享字节立即释放。

不要直接删除 /var/lib/containerd 下看起来“没用”的 snapshot 或 blob 目录,这可能破坏元数据引用。应通过管理 API、工具和上层 kubelet 的回收机制处理,再检查实际磁盘空间。

Daemon 与容器生命周期
#

shim 将运行任务与 containerd daemon 的生命周期部分解耦,因此 daemon 重启通常不要求业务进程跟着退出;这不代表升级和重启完全无影响,创建、查询等管理操作会暂时受影响。shim 故障、节点重启以及 systemd 单元的停止策略也可能产生不同结果。

排查时可以分层检查:镜像获取失败看 Registry/凭据/证书;snapshot 失败看插件、磁盘和挂载;Task 创建失败看 shim/runc 及 OCI 配置;sandbox 失败还要检查 CNI、pause 镜像和 sandbox controller。

官方资料
#

参考:
#

Related

性能优化
·7 mins
Kubernetes Scheduler
·11 mins
Kubernetes List & Watch
·11 mins