containerd 开源项目教程
项目介绍
containerd 是一个行业标准的容器运行时,强调简单性、健壮性和可移植性。它作为 Linux 和 Windows 的守护进程,可以管理其主机系统的完整容器生命周期,包括镜像传输和存储、容器执行和监控、低级存储和网络附加等。containerd 是 CNCF 的成员,具有“毕业”状态。它被设计为嵌入到更大的系统中,而不是直接使用。
项目快速启动
安装 containerd
首先,确保你的系统满足运行 containerd 的最低要求。对于 Linux,建议使用 4.x 或更高版本的内核。
# 下载并安装 containerd
wget https://github.com/containerd/containerd/releases/download/v1.7.20/containerd-1.7.20-linux-amd64.tar.gz
tar -xvf containerd-1.7.20-linux-amd64.tar.gz -C /usr/local
启动 containerd 服务
# 启动 containerd 服务
sudo systemctl start containerd
sudo systemctl enable containerd
使用 containerd 拉取和运行容器
package main
import (
"context"
"log"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/oci"
)
func main() {
client, err := containerd.New("/run/containerd/containerd.sock")
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx := context.Background()
// 拉取镜像
image, err := client.Pull(ctx, "docker.io/library/redis:latest", containerd.WithPullUnpack)
if err != nil {
log.Fatal(err)
}
// 创建容器
container, err := client.NewContainer(
ctx,
"redis-master",
containerd.WithNewSnapshot("redis-rootfs", image),
containerd.WithNewSpec(oci.WithImageConfig(image)),
)
if err != nil {
log.Fatal(err)
}
defer container.Delete(ctx, containerd.WithSnapshotCleanup)
// 创建任务
task, err := container.NewTask(ctx, cio.NewCreator(cio.WithStdio))
if err != nil {
log.Fatal(err)
}
defer task.Delete(ctx)
// 启动任务
if err := task.Start(ctx); err != nil {
log.Fatal(err)
}
log.Printf("Container %s started with PID %d\n", container.ID(), task.Pid())
}
应用案例和最佳实践
使用 containerd 管理多个容器
containerd 支持同时管理多个容器,适用于需要高并发和高可用性的场景。以下是一个示例,展示如何使用 containerd 创建多个容器:
for i := 0; i < 10; i++ {
id := fmt.Sprintf("id-%d", i)
container, err := client.NewContainer(
ctx,
id,
containerd.WithNewSnapshot(id, image),
containerd.WithNewSpec(oci.WithImageConfig(image)),
)
if err != nil {
log.Fatal(err)
}
defer container.Delete(ctx, containerd.WithSnapshotCleanup)
task, err := container.NewTask(ctx, cio.NewCreator(cio.WithStdio))
if err != nil {
log.Fatal(err)
}
defer task.Delete(ctx)
if err := task.Start(ctx); err != nil {
log.Fatal(err)
}
log.Printf("Container %s started with PID %d\n", container.ID(), task.Pid())
}
使用 containerd 进行镜像管理
containerd 提供了强大的镜像管理功能,可以方便地拉取、存储和删除镜像。以下是一个示例,展示如何使用 containerd 管理镜像:
// 拉取镜像
image, err := client.Pull(