当前位置: 首页 > news >正文

【云基础】容器管理工具Containerd

容器管理工具Containerd

一、Containerd介绍

Containerd 是开源容器运行时,属 CNCF 毕业项目,聚焦容器全生命周期管理,是 Docker、Kubernetes 等上层平台的底层核心支撑。

Containerd简介
核心定位

作为 “底层桥梁”,屏蔽操作系统差异,为上层工具提供统一的容器操作接口,专注 “镜像管理 + 容器管控” 两大核心,不冗余非必要功能。

关键能力
  1. 镜像管理:拉取 / 推送镜像、存储镜像分层数据,为容器启动做准备;
  2. 容器生命周期管控:创建、启动、停止、销毁容器,分配资源并隔离环境;
  3. 跨平台适配:支持 Linux(依赖 runc)、Windows 系统,适配不同容器类型。
与主流工具的关系
  • Docker:Docker 提供 docker run 等用户命令,底层容器操作调用 Containerd 实现;
  • Kubernetes:K8s 负责集群调度,单个节点的容器管理(如启动、拉镜像)通过 Containerd 完成。
核心优势

轻量(资源占用低)、稳定(生产级可靠性)、可扩展(插件化架构),是云原生生态的标准底层运行时选择。

Containerd架构
架构图

在这里插入图片描述

  • Containerd 采用标准的 C/S 架构

    • 服务端通过 GRPC 协议提供稳定的 API
    • 客户端通过调用服务端的 API 进行高级的操作
  • 为了实现解耦,Containerd 将不同的职责划分给不同的组件,每个组件就相当于一个子系统(subsystem)。连接不同子系统的组件被称为模块。

  • Containerd 两大子系统为:

    • Bundle : 在 Containerd 中,Bundle 包含了配置、元数据和根文件系统数据,你可以理解为容器的文件系统。而 Bundle 子系统允许用户从镜像中提取和打包 Bundles。
    • Runtime : Runtime 子系统用来执行 Bundles,比如创建容器。
  • 其中,每一个子系统的行为都由一个或多个模块协作完成(架构图中的 Core 部分)。每一种类型的模块都以插件的形式集成到 Containerd 中,而且插件之间是相互依赖的。例如,上图中的每一个长虚线的方框都表示一种类型的插件,包括 Service Plugin、MetadataPlugin、GC Plugin、Runtime Plugin 等,其中 Service Plugin 又会依赖 Metadata Plugin、GCPlugin 和 Runtime Plugin。每一个小方框都表示一个细分的插件,例如 Metadata Plugin 依赖Containers Plugin、Content Plugin 等。

常用插件
  • Content Plugin : 提供对镜像中可寻址内容的访问,所有不可变的内容都被存储在这里。

  • Snapshot Plugin : 用来管理容器镜像的文件系统快照。镜像中的每一个 layer 都会被解压成文件系统快照,类似于 Docker 中的 graphdriver 。

  • Metrics : 暴露各个组件的监控指标。

在这里插入图片描述

架构缩略图

Containerd 被分为三个大块: Storage 、 Metadata 和 Runtime

在这里插入图片描述

二、Containerd安装

操作系统: CentOS Stream 8

1.YUM方式安装

基于 CentOS-Stream-8模板制作.md 制作的模板克隆一台虚拟机命名为Containerd

在这里插入图片描述

安装必要工具

# 如果模板已安装,那么这步可以忽略
[root@localhost ~]# yum install -y yum-utils device-mapper-persistent-data lvm2 vim

安装Containerd

# 1.获取阿里云YUM源
[root@localhost ~]# yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
Adding repo from: https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
[root@localhost ~]# yum makecache
Docker CE Stable - x86_64                                                 398 kB/s |  66 kB     00:00
CentOS Stream 8 - BaseOS                                                   27 kB/s | 3.9 kB     00:00
CentOS Stream 8 - AppStream                                                24 kB/s | 4.4 kB     00:00
Metadata cache created.# 2.查看YUM源中Containerd软件
[root@localhost ~]# yum list | grep containerd
containerd.io.x86_64                                   1.6.32-3.1.el8                                        docker-ce-stable# 3.安装Containerd.io软件,即可安装Containerd
[root@localhost ~]# yum -y install containerd.io# 4.使用rpm -qa命令查看是否安装
[root@localhost ~]# rpm -qa | grep containerd
containerd.io-1.6.32-3.1.el8.x86_64# 5.设置containerd服务启动及开机自启动
[root@localhost ~]# systemctl enable containerd --now
Created symlink /etc/systemd/system/multi-user.target.wants/containerd.service → /usr/lib/systemd/system/containerd.service.[root@localhost ~]# systemctl status containerd
● containerd.service - containerd container runtimeLoaded: loaded (/usr/lib/systemd/system/containerd.service; enabled; vendor preset: disabled)Active: active (running) since Thu 2025-09-11 17:15:08 CST; 17s ago
...........# 6.验证
# 安装Containerd时ctr命令亦可使用,ctr命令主要用于管理容器及容器镜像等。
# 使用ctr命令查看Containerd客户端及服务端相关信息
[root@localhost ~]# ctr version
Client:Version:  1.6.32Revision: 8b3b7ca2e5ce38e8f31a34f35b2b68ceb8470d89Go version: go1.21.10Server:Version:  1.6.32Revision: 8b3b7ca2e5ce38e8f31a34f35b2b68ceb8470d89UUID: 68510217-aad5-4cd4-9625-e68a146f0391
2.二进制方式安装

Containerd有两种安装包:

  • 第一种是containerd-xxx,这种包用于单机测试没问题,不包含runC,需要提前安装。

  • 第二种是cri-containerd-cni-xxxx,包含runc和k8s里的所需要的相关文件。k8s集群里需要用到此包。虽然包含runC,但是依赖系统中的seccomp(安全计算模式,是一种限制容器调用系统资源的模式。)

安装Containerd

# 1.下载Containerd安装包
wget https://github.com/containerd/containerd/re1eases/down1oad/v1.6.32/cri containerd-cni-1.6.32-1inux-amd64.tar.gz# 2.安装containerd
[root@localhost ~]# mkdir containerd
[root@localhost ~]# tar xf cri-containerd-cni-1.6.32-linux-amd64.tar.gz -C containerd/
[root@localhost ~]# cd containerd/
[root@localhost containerd]# ls
cri-containerd.DEPRECATED.txt etc opt usr
[root@localhost containerd]# tree
.
├── cri-containerd.DEPRECATED.txt
├── etc
│   ├── cni
│   │   └── net.d
│   │       └── 10-containerd-net.conflist
│   ├── crictl.yaml
│   └── systemd
│       └── system
│           └── containerd.service
├── opt
│   ├── cni
│   │   └── bin
│   │       ├── bandwidth
│   │       ├── bridge
│   │       ├── dhcp
│   │       ├── firewall
│   │       ├── host-device
│   │       ├── host-local
│   │       ├── ipvlan
│   │       ├── loopback
│   │       ├── macvlan
│   │       ├── portmap
│   │       ├── ptp
│   │       ├── sbr
│   │       ├── static
│   │       ├── tuning
│   │       ├── vlan
│   │       └── vrf
│   └── containerd
│       └── cluster
│           ├── gce
│           │   ├── cloud-init
│           │   │   ├── master.yaml
│           │   │   └── node.yaml
│           │   ├── cni.template
│           │   ├── configure.sh
│           │   └── env
│           └── version
└── usr└── local├── bin│   ├── containerd│   ├── containerd-shim│   ├── containerd-shim-runc-v1│   ├── containerd-shim-runc-v2│   ├── containerd-stress│   ├── crictl│   ├── critest│   ├── ctd-decoder│   └── ctr└── sbin└── runc16 directories, 36 files#查看containerd.service文件,了解containerd文件安装位置
[root@localhost containerd]# cat etc/systemd/system/containerd.service
# Copyright The containerd Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target local-fs.target      [Service]
ExecStartPre=-/sbin/modprobe overlay
ExecStart=/usr/local/bin/containerd        # 查看此位置,把containerd二进制文件放置于此处即可完成安装。Type=notify
Delegate=yes
KillMode=process
Restart=always
RestartSec=5
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNPROC=infinity
LimitCORE=infinity
LimitNOFILE=infinity
# Comment TasksMax if your systemd version does not supports it.
# Only systemd 226 and above support this version.
TasksMax=infinity
OOMScoreAdjust=-999[Install]
WantedBy=multi-user.target# 复制containerd运行时文件至系统
[root@localhost containerd]# cp usr/local/bin/* /usr/local/bin# 添加containerd.service文件至系统
[root@localhost containerd]# cp etc/systemd/system/containerd.service /usr/lib/systemd/system/containerd.service# 生成containerd模块配置文件,可以自定义一下配置,如有私有镜像仓库等,按需配置
[root@localhost containerd]# mkdir /etc/containerd
[root@localhost containerd]# containerd config default > /etc/containerd/config.toml# 启动containerd并验证
[root@localhost ~]# systemctl enable containerd --now
[root@localhost ~]# systemctl status containerd
[root@localhost ~]# ctr version
Client:Version: v1.6.32Revision: 8b3b7ca2e5ce38e8f31a34f35b2b68ceb8470d89Go version: go1.21.10
Server:Version: v1.6.32Revision: 8b3b7ca2e5ce38e8f31a34f35b2b68ceb8470d89UUID: 3ece67b1-4d8e-4059-afae-b837672ede83

安装runC

由于二进制包中提供的runC默认需要系统中安装seccomp支持,需要单独安装,且不同版本runC对seccomp版本要求一致,所以建议单独下载runC 二进制包进行安装,里面包含了seccomp模块支持。下载地址:https://github.com/opencontainers/runc/releases

# 使用wget下载runc
[root@localhost ~]# wget https://github.com/opencontainers/runc/releases/download/v1.3.0/runc.amd64# 安装runc
[root@localhost ~]# mv runc.amd64 /usr/sbin/runc# 为runc添加可执行权限
[root@localhost ~]# chmod +x /usr/sbin/runc# 使用runc命令验证是否安装成功
[root@localhost ~]# runc -v
runc version 1.3.0
commit: v1.3.0-0-g4ca628d1
spec: 1.2.1
go: go1.23.8
libseccomp: 2.5.6

三、Containerd容器镜像管理

帮助命令
  • docker使用docker images命令管理镜像

  • 单机containerd使用ctr images命令管理镜像,containerd本身的CLI

  • k8s中containerd使用crictl images命令管理镜像,Kubernetes社区的专用CLI工具

# 命令帮助
[root@localhost ~]# ctr --help
NAME:ctr -_______/ /______/ ___/ __/ ___/
/ /__/ /_/ /
\___/\__/_/containerd CLIUSAGE:ctr [global options] command [command options] [arguments...]VERSION:1.6.32DESCRIPTION:ctr is an unsupported debug and administrative client for interacting
with the containerd daemon. Because it is unsupported, the commands,
options, and operations are not guaranteed to be backward compatible or
stable from release to release of the containerd project.COMMANDS:plugins, plugin            provides information about containerd pluginsversion                    print the client and server versionscontainers, c, container   manage containerscontent                    manage contentevents, event              display containerd eventsimages, image, i           manage imagesleases                     manage leasesnamespaces, namespace, ns  manage namespacespprof                      provide golang pprof outputs for containerdrun                        run a containersnapshots, snapshot        manage snapshotstasks, t, task             manage tasksinstall                    install a new packageoci                        OCI toolsdeprecationsshim                       interact with a shim directlyhelp, h                    Shows a list of commands or help for one commandGLOBAL OPTIONS:--debug                      enable debug output in logs--address value, -a value    address for containerd's GRPC server (default: "/run/containerd/containerd.sock") [$CONTAINERD_ADDRESS]--timeout value              total timeout for ctr commands (default: 0s)--connect-timeout value      timeout for connecting to containerd (default: 0s)--namespace value, -n value  namespace to use with commands (default: "default") [$CONTAINERD_NAMESPACE]--help, -h                   show help--version, -v                print the version# 子命令帮助   
[root@localhost ~]# ctr images --help
NAME:ctr images - manage imagesUSAGE:ctr images command [command options] [arguments...]COMMANDS:check                    check existing images to ensure all content is available locallyexport                   export imagesimport                   import imageslist, ls                 list images known to containerdmount                    mount an image to a target pathunmount                  unmount the image from the targetpull                     pull an image from a remotepush                     push an image to a remotedelete, del, remove, rm  remove one or more images by referencetag                      tag an imagelabel                    set and clear labels for an imageconvert                  convert an imageOPTIONS:--help, -h  show help
查看镜像
[root@docker ~]# ctr images list
REF TYPE DIGEST SIZE PLATFORMS LABELS
[root@docker ~]# ctr images ls
REF TYPE DIGEST SIZE PLATFORMS LABELS
[root@docker ~]# ctr image list
REF TYPE DIGEST SIZE PLATFORMS LABELS
[root@docker ~]# ctr image ls
REF TYPE DIGEST SIZE PLATFORMS LABELS
[root@docker ~]# ctr i list
REF TYPE DIGEST SIZE PLATFORMS LABELS
[root@docker ~]# ctr i ls
REF TYPE DIGEST SIZE PLATFORMS LABELS
下载镜像

containerd支持oci标准的镜像,所以可以直接使用docker官方或dockerfile构建的镜像

# 这里ctr命令pull镜像时,不能直接把镜像名字写成nginx:alpine
[root@localhost ~]# ctr images pull 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest# 验证现象
[root@localhost ~]# ctr image ls
REF                                                                                TYPE                                    DIGEST                                                                  SIZE     PLATFORMS                                                                                                               LABELS
054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest application/vnd.oci.image.index.v1+json sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e 69.0 MiB linux/386,linux/amd64,linux/arm/v5,linux/arm/v7,linux/arm64/v8,linux/mips64le,linux/ppc64le,linux/s390x,unknown/unknown -
镜像挂载

方便查看镜像中包含的内容

# 挂载
[root@localhost ~]# ctr images mount 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest /mnt
sha256:6d03e4aefb16ea9e0d73cacb9a9fcb8f7fb3a806c41606600cab179aa381550f
/mnt# 查看挂载
[root@localhost ~]# ls /mnt
bin   dev                  docker-entrypoint.sh  home  lib64  mnt  proc  run   srv  tmp  var
boot  docker-entrypoint.d  etc                   lib   media  opt  root  sbin  sys  usr# 卸载
[root@localhost ~]# umount /mnt
镜像导出
# --platform linux/amd64,导出指定平台镜像:指定要导出的镜像平台为 Linux 系统的 amd64 架构
[root@localhost ~]# ctr i export --platform linux/amd64 nginx.img 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest[root@localhost ~]# ls
nginx.img
镜像删除
# ctr image rm帮助
[root@localhost ~]# ctr image rm --help
NAME:ctr images delete - remove one or more images by referenceUSAGE:ctr images delete [command options] [flags] <ref> [<ref>, ...]DESCRIPTION:remove one or more images by referenceOPTIONS:--sync  Synchronously remove image and all associated resources# 删除指定镜像
[root@localhost ~]# ctr image rm 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest
054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest# 验证
[root@localhost ~]# ctr image ls
REF TYPE DIGEST SIZE PLATFORMS LABELS
镜像导入
# 导入镜像
[root@localhost ~]# ctr images import --platform linux/amd64 nginx.img
unpacking 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest (sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e)...done# 验证
[root@localhost ~]# ctr image ls
REF                                                                                TYPE                                    DIGEST                                                                  SIZE     PLATFORMS                                                                                                               LABELS
054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest application/vnd.oci.image.index.v1+json sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e 69.0 MiB linux/386,linux/amd64,linux/arm/v5,linux/arm/v7,linux/arm64/v8,linux/mips64le,linux/ppc64le,linux/s390x,unknown/unknown -
修改镜像tag
# 把054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest 修改为 nginx:latest
[root@localhost ~]# ctr images tag 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest nginx:latest
nginx:latest# 验证
[root@localhost ~]# ctr image ls
REF                                                                                TYPE                                    DIGEST                                                                  SIZE     PLATFORMS                                                                                                               LABELS
054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest application/vnd.oci.image.index.v1+json sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e 69.0 MiB linux/386,linux/amd64,linux/arm/v5,linux/arm/v7,linux/arm64/v8,linux/mips64le,linux/ppc64le,linux/s390x,unknown/unknown -
nginx:latest                                                                       application/vnd.oci.image.index.v1+json sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e 69.0 MiB linux/386,linux/amd64,linux/arm/v5,linux/arm/v7,linux/arm64/v8,linux/mips64le,linux/ppc64le,linux/s390x,unknown/unknown -

四、Containerd容器管理

# 1.获取命令帮助
[root@localhost ~]# ctr --help
NAME:ctr -_______/ /______/ ___/ __/ ___/
/ /__/ /_/ /
\___/\__/_/containerd CLIUSAGE:ctr [global options] command [command options] [arguments...]VERSION:1.6.32DESCRIPTION:ctr is an unsupported debug and administrative client for interacting
with the containerd daemon. Because it is unsupported, the commands,
options, and operations are not guaranteed to be backward compatible or
stable from release to release of the containerd project.COMMANDS:plugins, plugin            provides information about containerd pluginsversion                    print the client and server versionscontainers, c, container   manage containerscontent                    manage contentevents, event              display containerd eventsimages, image, i           manage imagesleases                     manage leasesnamespaces, namespace, ns  manage namespacespprof                      provide golang pprof outputs for containerdrun                        run a containersnapshots, snapshot        manage snapshotstasks, t, task             manage tasksinstall                    install a new packageoci                        OCI toolsdeprecationsshim                       interact with a shim directlyhelp, h                    Shows a list of commands or help for one commandGLOBAL OPTIONS:--debug                      enable debug output in logs--address value, -a value    address for containerd's GRPC server (default: "/run/containerd/containerd.sock") [$CONTAINERD_ADDRESS]--timeout value              total timeout for ctr commands (default: 0s)--connect-timeout value      timeout for connecting to containerd (default: 0s)--namespace value, -n value  namespace to use with commands (default: "default") [$CONTAINERD_NAMESPACE]--help, -h                   show help--version, -v                print the version# 获取创建静态容器命令帮助 使用`ctrcontainer create `命令创建容器后,容器并没有处于运行状态,其只是一个静态的容器。这个container 对象只是包含了运行一个容器所需的资源及配置的数据结构,例如: namespaces、rootfs 和容器的配置都已经初始化成功了,只是用户进程(本案例为nginx)还没有启动。需要使用`ctr tasks`命令才能获取一个动态容器。
[root@localhost ~]# ctr container --help
NAME:ctr containers - manage containersUSAGE:ctr containers command [command options] [arguments...]COMMANDS:create                   create containerdelete, del, remove, rm  delete one or more existing containersinfo                     get info about a containerlist, ls                 list containerslabel                    set and clear labels for a containercheckpoint               checkpoint a containerrestore                  restore a container from checkpointOPTIONS:--help, -h  show help# 使用`ctr run`命令可以创建一个静态容器并使其运行。一步到位运行容器。
[root@localhost ~]# ctr run --help
NAME:ctr run - run a containerUSAGE:ctr run [command options] [flags] Image|RootFS ID [COMMAND] [ARG...]OPTIONS:--rm                                    remove the container after running, cannot be used with --detach--null-io                               send all IO to /dev/null--log-uri value                         log uri--detach, -d                            detach from the task after it has started execution, cannot be used with --rm--fifo-dir value                        directory used for storing IO FIFOs--cgroup value                          cgroup path (To disable use of cgroup, set to "" explicitly)--platform value                        run image for specific platform--cni                                   enable cni networking for the container--runc-binary value                     specify runc-compatible binary--runc-root value                       specify runc-compatible root--runc-systemd-cgroup                   start runc with systemd cgroup manager--uidmap container-uid:host-uid:length  run inside a user namespace with the specified UID mapping range; specified with the format container-uid:host-uid:length--gidmap container-gid:host-gid:length  run inside a user namespace with the specified GID mapping range; specified with the format container-gid:host-gid:length--remap-labels                          provide the user namespace ID remapping to the snapshotter via label options; requires snapshotter support--cpus value                            set the CFS cpu quota (default: 0)--cpu-shares value                      set the cpu shares (default: 1024)--snapshotter value                     snapshotter name. Empty value stands for the default value. [$CONTAINERD_SNAPSHOTTER]--snapshotter-label value               labels added to the new snapshot for this container.--config value, -c value                path to the runtime-specific spec config file--cwd value                             specify the working directory of the process--env value                             specify additional container environment variables (e.g. FOO=bar)--env-file value                        specify additional container environment variables in a file(e.g. FOO=bar, one per line)--label value                           specify additional labels (e.g. foo=bar)--annotation value                      specify additional OCI annotations (e.g. foo=bar)--mount value                           specify additional container mount (e.g. type=bind,src=/tmp,dst=/host,options=rbind:ro)--net-host                              enable host networking for the container--privileged                            run privileged container--read-only                             set the containers filesystem as readonly--runtime value                         runtime name (default: "io.containerd.runc.v2")--runtime-config-path value             optional runtime config path--tty, -t                               allocate a TTY for the container--with-ns value                         specify existing Linux namespaces to join at container runtime (format '<nstype>:<path>')--pid-file value                        file path to write the task's pid--gpus value                            add gpus to the container--allow-new-privs                       turn off OCI spec's NoNewPrivileges feature flag--memory-limit value                    memory limit (in bytes) for the container (default: 0)--device value                          file path to a device to add to the container; or a path to a directory tree of devices to add to the container--cap-add value                         add Linux capabilities (Set capabilities with 'CAP_' prefix)--cap-drop value                        drop Linux capabilities (Set capabilities with 'CAP_' prefix)--seccomp                               enable the default seccomp profile--seccomp-profile value                 file path to custom seccomp profile. seccomp must be set to true, before using seccomp-profile--apparmor-default-profile value        enable AppArmor with the default profile with the specified name, e.g. "cri-containerd.apparmor.d"--apparmor-profile value                enable AppArmor with an existing custom profile--rdt-class value                       name of the RDT class to associate the container with. Specifies a Class of Service (CLOS) for cache and memory bandwidth management.--rootfs                                use custom rootfs that is not managed by containerd snapshotter--no-pivot                              disable use of pivot-root (linux only)--cpu-quota value                       Limit CPU CFS quota (default: -1)--cpu-period value                      Limit CPU CFS period (default: 0)--rootfs-propagation value              set the propagation of the container rootfs# 2.查看容器(container表示静态容器,可用c缩写代表container)
[root@localhost ~]# ctr container ls     # 可以简写为 ctr c ls
CONTAINER    IMAGE    RUNTIME# 3.查看任务(task表示容器里跑的进程, 可用t缩写代表task)
[root@localhost ~]# ctr task ls      # 可以简写为 ctr t ls
TASK    PID    STATUS# 4.创建静态容器
# 使用 ctr 创建一个基于 nginx:latest 镜像的容器,命名为 nginx1
# 此时容器处于"已创建"状态(未运行),仅完成了初始化配置
[root@localhost ~]# ctr container create nginx:latest nginx1# 列出所有容器,验证 nginx1 是否创建成功
# 输出显示容器 nginx1 已存在,使用的镜像为 nginx:latest,运行时为 io.containerd.runc.v2(containerd 推荐的运行时)
[root@localhost ~]# ctr container ls
CONTAINER    IMAGE           RUNTIME
nginx1       nginx:latest    io.containerd.runc.v2# 查看容器 nginx1 的详细信息(配置、状态等)
# 输出内容包括:容器 ID、创建时间、镜像信息、运行时配置、挂载点、环境变量、网络设置等元数据
[root@localhost ~]# ctr container info nginx1# 5.静态容器启动为动态容器
[root@localhost ~]# ctr task ls
TASK    PID    STATUS
[root@localhost ~]# ctr task start -d nginx1    #启动task,即表时在容器中运行了进程,即为动态容器 -d 后台
[root@localhost ~]# ctr task ls     #容器是以宿主机进程的方式存在的
TASK      PID     STATUS
nginx1    2537    RUNNING[root@localhost ~]# ps aux | grep 2537
root        2537  0.0  0.1  11476  7332 ?        Ss   19:55   0:00 nginx: master process nginx -g daemon off;
root        2583  0.0  0.0  12216  1104 pts/0    S+   19:56   0:00 grep --color=auto 2537# 6.进入容器操作
[root@localhost ~]# ctr task exec --exec-id $RANDOM -t nginx1 /bin/sh      #为exec进程设定一个id,可以随意输入,只要保证唯一即可,也可使用$RANDOM变量
# exit# 7.直接运行一个动态容器
# --net-host 代表容器的IP就是宿主机的IP(相当于docker里的host类型网络)
[root@localhost ~]# ctr run -d --net-host nginx:latest nginx2# 8.暂停容器
[root@localhost ~]# ctr tasks pause nginx2
[root@localhost ~]# ctr task ls
TASK      PID     STATUS
nginx2    2644    PAUSED       #状态为PAUSED,表示暂停
nginx1    2537    RUNNING# 9.恢复容器
[root@localhost ~]# ctr tasks resume nginx2
[root@localhost ~]# ctr task ls
TASK      PID     STATUS
nginx1    2537    RUNNING
nginx2    2644    RUNNING     #恢复RUNNING# 10.停止容器
[root@localhost ~]# ctr tasks kill nginx2
[root@localhost ~]# ctr task ls
TASK      PID     STATUS
nginx1    2537    RUNNING
nginx2    2644    STOPPED     #容器停止后STATUS为STOPPED# 11.删除容器
#必须先停止tasks或先删除task,再删除容器
[root@localhost ~]# ctr tasks delete nginx2
[root@localhost ~]# ctr task ls
TASK      PID     STATUS
nginx1    2537    RUNNING# 查看静态容器,确认其还存在于系统中
[root@localhost ~]# ctr container ls
CONTAINER    IMAGE           RUNTIME
nginx1       nginx:latest    io.containerd.runc.v2
nginx2       nginx:latest    io.containerd.runc.v2# 使用 ctr 工具删除名为 nginx2 的容器
# 若容器不存在,会提示错误;若存在则直接删除(需注意:运行中的容器可能需要先停止再删除)
[root@localhost ~]# ctr container delete nginx2# 列出当前所有容器,验证删除操作结果
# 输出显示仅保留了名为 nginx1 的容器,说明 nginx2 已成功删除
[root@localhost ~]# ctr container ls
CONTAINER    IMAGE           RUNTIME
nginx1       nginx:latest    io.containerd.runc.v2  

五、Containerd NameSpace管理

containerd中namespace的作用为:隔离运行的容器,可以实现运行多个容器

# 1.列出已有namespace
[root@localhost ~]# ctr namespace ls
NAME    LABELS
default      #containerd默认工作在default命名空间
# moby       docker默认工作在moby空间# 2.创建namespace
[root@localhost ~]# ctr namespace ls
NAME    LABELS
default
myns
testns# 3.删除namespace
[root@localhost ~]# ctr namespace rm testns
testns
[root@localhost ~]# ctr namespace ls
NAME    LABELS
default
myns# 4.查看指定namespace中的所有镜像
[root@localhost ~]# ctr -n myns images ls
REF TYPE DIGEST SIZE PLATFORMS LABELS# 5.查看指定namespace中是否有用户进程在运行
[root@localhost ~]# ctr -n myns tasks ls
TASK    PID    STATUS# 6.在指定namespace中下载容器镜像
[root@localhost ~]# ctr -n myns images pull 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest
054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest: resolved       |++++++++++++++++++++++++++++++++++++++|
index-sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e:      done           |++++++++++++++++++++++++++++++++++++++|
manifest-sha256:27637a97e3d1d0518adc2a877b60db3779970f19474b6e586ddcbc2d5500e285:   done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:6c50e4e0c4393a7c1dc665d7c0f5b717d184ead14a9a0cfd50acd7997fe5e70d:      done           |++++++++++++++++++++++++++++++++++++++|
config-sha256:41f689c209100e6cadf3ce7fdd02035e90dbd1d586716bf8fc6ea55c365b2d81:     done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:899c83fc198bc29704e0f259db984cde12bfbb7cb60363667b108955b05fdd7a:      done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:a785b80f5a670dcc22bd75e3ffd6463d1b27c37f53a799479bf8ac95d2330952:      done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:d107e437f7299a0db6425d4e37f44fa779f7917ecc8daf1e87128ee91b9ed3d3:      done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:f72106e8650736e17bf673e22947b69f0074b76be40d5a728d0704a762d0d285:      done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:f1c4d397f477546f880aadb7faeeee8eaa1d40e3ded29e62b598f64acf629912:      done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:cb497a329a815b4a2fe3b785e16e4589f3fe899a7d46834671125ef0b21e85ba:      done           |++++++++++++++++++++++++++++++++++++++|
elapsed: 1.5 s                                                                      total:  12.2 K (8.2 KiB/s)
unpacking linux/amd64 sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e...
done: 2.27368486s
[root@localhost ~]# ctr -n myns images ls
REF                                                                                TYPE                                    DIGEST                                                                  SIZE     PLATFORMS                                                                                                               LABELS
054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest application/vnd.oci.image.index.v1+json sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e 69.0 MiB linux/386,linux/amd64,linux/arm/v5,linux/arm/v7,linux/arm64/v8,linux/mips64le,linux/ppc64le,linux/s390x,unknown/unknown -# 7.在指定namespace中创建静态容器
[root@localhost ~]# ctr -n myns container create 054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest mynginx# 8.查看在指定namespace中创建的容器
[root@localhost ~]# ctr -n myns container ls
CONTAINER    IMAGE                                                                                 RUNTIME
mynginx      054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com/library/nginx:latest    io.containerd.runc.v2# 在myns命名空间后台启动名为mynginx的任务
[root@localhost ~]# ctr -n myns task start -d mynginx# 查看myns命名空间下的任务列表(显示mynginx正在运行,PID为1896)
[root@localhost ~]# ctr -n myns tasks ls
TASK       PID     STATUS
mynginx    1896    RUNNING

六、nerdctl实践

nerdctl安装

我们推荐使用 nerdctl 管理containerd,命令语法与 docker 一致。

截止 2023-05-24 最新版本是 v 1.4.0

github项目地址:https://github.com/containerd/nerdctl/releases

cni插件项目地址:https://github.com/containernetworking/plugins/releases

# 下载并安装
[root@localhost ~]# wget https://github.com/containerd/nerdctl/releases/download/v1.4.0/nerdctl-1.4.0-linux-amd64.tar.gz
[root@localhost ~]# tar -xf nerdctl-1.4.0-linux-amd64.tar.gz -C /usr/bin/# 配置nerdctl命令自动补全
[root@localhost ~]# nerdctl completion bash > /etc/bash_completion.d/nerdctl
[root@localhost ~]# source /etc/bash_completion.d/nerdctl# 下载nerdctl所需要的cni插件
[root@localhost ~]# wget https://github.com/containernetworking/plugins/releases/download/v1.3.0/cni-plugins-linux-amd64-v1.3.0.tgz[root@localhost ~]# mkdir -p /opt/cni/bin
[root@localhost ~]# tar -xf cni-plugins-linux-amd64-v1.3.0.tgz -C /opt/cni/bin

配置镜像加速

# 编辑containerd的配置文件config.toml,如果不存在,需要手动生成,方法containerd configdefault > /etc/containerd/config.toml,在配置文件中搜索关键字“config_path”,在其下面添加镜像加速参数
[root@docker ~]# containerd config default > /etc/containerd/config.toml
[root@localhost ~]# vim /etc/containerd/config.toml[plugins."io.containerd.grpc.v1.cri".registry]config_path = "/etc/containerd/certs.d"
[root@control ~]# mkdir -p /etc/containerd/certs.d/docker.io
[root@localhost ~]# vim /etc/containerd/certs.d/docker.io/hosts.toml
server = "https://054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com"
[host."https://054b8ac70e8010d90f2ac00ef29e6580.mirror.swr.myhuaweicloud.com"]capabilities = ["pull", "resolve"]# 重启containerd服务生效
[root@control ~]# systemctl restart containerd
nerdctl管理镜像
[root@localhost ~]# nerdctl image <tab><tab>
build    (Build an image from a Dockerfile. Needs buildkitd to be running.)
convert  (convert an image)
decrypt  (decrypt an image)
encrypt  (encrypt image layers)
history  (Show the history of an image)
inspect  (Display detailed information on one or more images.)
load     (Load an image from a tar archive or STDIN)
ls       (List images)
prune    (Remove unused images)
pull     (Pull an image from a registry. Optionally specify "ipfs://" or "ipns://" scheme to pull image …)
push     (Push an image or a repository to a registry. Optionally specify "ipfs://" or "ipns://" scheme …)
rm       (Remove one or more images)
save     (Save one or more images to a tar archive (streamed to STDOUT by default))
tag      (Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE)
ls

作用:查看本地镜像清单。
示例:

[root@localhost ~]# nerdctl image ls
REPOSITORY       TAG       IMAGE ID        CREATED         PLATFORM       SIZE         BLOB SIZE# 可简写如下
[root@localhost ~]# nerdctl images
pull

作用:从网络上下载镜像。
示例:

#下载镜像busybox
[root@localhost ~]# nerdctl image pull busybox
docker.io/library/busybox:latest:                                                 resolved       |++++++++++++++++++++++++++++++++++++++|
index-sha256:d82f458899c9696cb26a7c02d5568f81c8c8223f8661bb2a7988b269c8b9051e:    done           |++++++++++++++++++++++++++++++++++++++|
manifest-sha256:182014572d8981d8323fe9944876f63b39694e16ce08ae6296e97686c52b150c: done           |++++++++++++++++++++++++++++++++++++++|
config-sha256:0ed463b26daee791b094dc3fff25edb3e79f153d37d274e5c2936923c38dac2b:   done           |++++++++++++++++++++++++++++++++++++++|
elapsed: 2.9 s                                                                    total:   0.0 B (0.0 B/s)
# 可简写如下下载httpd
# [root@localhost ~]# nerdctl pull httpd[root@localhost ~]# nerdctl image ls
REPOSITORY                                                                     TAG       IMAGE ID        CREATED       PLATFORM       SIZE         BLOB SIZE
busybox                                                                        latest    d82f458899c9    5 days ago    linux/amd64    4.3 MiB      2.1 MiB
rm

作用:删除本地不用的镜像。
示例:

[root@localhost ~]# nerdctl image rm busybox [root@localhost ~]# nerdctl images
REPOSITORY                                                                     TAG       IMAGE ID        CREATED       PLATFORM       SIZE         BLOB SIZE
tag

作用:给镜像打标签。
示例:

[root@localhost ~]# nerdctl tag busybox busybox_containerd[root@localhost ~]# nerdctl images
REPOSITORY                                                                     TAG       IMAGE ID        CREATED          PLATFORM       SIZE         BLOB SIZE
busybox                                                                        latest    d82f458899c9    5 days ago       linux/amd64    4.3 MiB      2.1 MiB
busybox_containerd                                                             latest    d82f458899c9    6 seconds ago    linux/amd64    4.3 MiB      2.1 MiB
save

作用:将本地镜像导出为文件。
示例:

[root@localhost ~]# nerdctl image save busybox -o busybox.tar
# 可简写为
# [root@localhost ~]# nerdctl save busybox -o busybox.tar# 删除镜像
[root@localhost ~]# nerdctl image rm busybox[root@localhost ~]# nerdctl images
REPOSITORY                                                                     TAG       IMAGE ID        CREATED           PLATFORM       SIZE         BLOB SIZE
busybox_containerd                                                             latest    d82f458899c9    12 minutes ago    linux/amd64    4.3 MiB      2.1 MiB
load

作用:导入tar文件中镜像。
示例:

[root@localhost ~]# nerdctl image load -i busybox.tar
unpacking docker.io/library/busybox:latest (sha256:d82f458899c9696cb26a7c02d5568f81c8c8223f8661bb2a7988b269c8b9051e)...
Loaded image: busybox:latest
# 可简写为
# [root@localhost ~]# nerdctl load -i busybox.tar[root@localhost ~]# nerdctl images
REPOSITORY                                                                     TAG       IMAGE ID        CREATED           PLATFORM       SIZE         BLOB SIZE
busybox                                                                        latest    d82f458899c9    48 seconds ago    linux/amd64    4.3 MiB      2.1 MiB
busybox_containerd                                                             latest    d82f458899c9    17 minutes ago    linux/amd64    4.3 MiB      2.1 MiB
history

作用:查看镜像构建时的历史命令层次结构。
示例:

[root@localhost ~]# nerdctl image history busybox
SNAPSHOT                                                                   CREATED          CREATED BY                           SIZE       COMMENT
sha256:80e840de630d08a6a1e0ee30e7c8378cf1ed6a424315d7e437f54780aee6bf5a    11 months ago    BusyBox 1.37.0 (glibc), Debian 13    4.3 MiB
inspect

作用:查看镜像详细信息。
示例:

[root@localhost ~]# nerdctl image inspect busybox
[{"Id": "sha256:0ed463b26daee791b094dc3fff25edb3e79f153d37d274e5c2936923c38dac2b","RepoTags": ["busybox:latest"],"RepoDigests": ["busybox@sha256:d82f458899c9696cb26a7c02d5568f81c8c8223f8661bb2a7988b269c8b9051e"],"Comment": "","Created": "2024-09-26T21:31:42Z","Author": "","Config": {"AttachStdin": false,"Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd": ["sh"]},"Architecture": "amd64","Os": "linux","Size": 4493312,"RootFS": {"Type": "layers","Layers": ["sha256:80e840de630d08a6a1e0ee30e7c8378cf1ed6a424315d7e437f54780aee6bf5a"]},"Metadata": {"LastTagTime": "0001-01-01T00:00:00Z"}}
]
prune

作用:删除所有未使用的镜像。
示例:

[root@localhost ~]# nerdctl image prune --all --force
Deleted Images:
Untagged: docker.io/library/busybox_containerd:latest
deleted: sha256:80e840de630d08a6a1e0ee30e7c8378cf1ed6a424315d7e437f54780aee6bf5a[root@localhost ~]# nerdctl image ls
REPOSITORY    TAG       IMAGE ID        CREATED           PLATFORM       SIZE         BLOB SIZE
nerdctl管理容器
帮助信息
[root@localhost ~]# nerdctl container --help
Manage containersUsage: nerdctl container [flags]Commands:commit   Create a new image from a container's changescp       Copy files/folders between a running container and the local filesystem.create   Create a new container. Optionally specify "ipfs://" or "ipns://" scheme to pull image from IPFS.exec     Run a command in a running containerinspect  Display detailed information on one or more containers.kill     Kill one or more running containerslogs     Fetch the logs of a container. Expected to be used with 'nerdctl run -d'.ls       List containerspause    Pause all processes within one or more containersport     List port mappings or a specific mapping for the containerprune    Remove all stopped containersrename   rename a containerrestart  Restart one or more running containersrm       Remove one or more containersrun      Run a command in a new container. Optionally specify "ipfs://" or "ipns://" scheme to pull image from IPFS.start    Start one or more running containersstop     Stop one or more running containersunpause  Unpause all processes within one or more containersupdate   Update one or more running containerswait     Block until one or more containers stop, then print their exit codes.Flags:-h, --help   help for containerSee also 'nerdctl --help' for the global flags such as '--namespace', '--snapshotter', and '--cgroup-manager'.
ls

作用:查看容器清单。
示例:

[root@localhost ~]# nerdctl container ls
CONTAINER ID    IMAGE    COMMAND    CREATED    STATUS    PORTS    NAMES
# 可简写为
# [root@localhost ~]# nerdctl ps# 使用-a选项查看所有容器,包括未运行的
[root@localhost ~]# nerdctl container ls -a
CONTAINER ID    IMAGE    COMMAND    CREATED    STATUS    PORTS    NAMES

常用选项:

  • -a, --all Show all containers (default shows just running)

  • -f, --filter strings Filter matches containers based on given conditions

  • –format string Format the output using the given Go template, e.g, ‘{{json .}}’, ‘wide’

run

作用:创建并运行容器。
示例:

[root@localhost ~]# nerdctl container run -it ubuntu
docker.io/library/ubuntu:latest:                                                  resolved       |++++++++++++++++++++++++++++++++++++++|
index-sha256:353675e2a41babd526e2b837d7ec780c2a05bca0164f7ea5dbbd433d21d166fc:    done           |++++++++++++++++++++++++++++++++++++++|
manifest-sha256:985be7c735afdf6f18aaa122c23f87d989c30bba4e9aa24c8278912aac339a8d: done           |++++++++++++++++++++++++++++++++++++++|
config-sha256:6d79abd4c96299aa91f5a4a46551042407568a3858b00ab460f4ba430984f62c:   done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:953cdd4133718b72c5d0a78e754c1405c02510fdb5237265f7955863f1757f83:    done           |++++++++++++++++++++++++++++++++++++++|
elapsed: 57.6s                                                                    total:  28.4 M (504.1 KiB/s)
root@440e564c529b:/# exit
exit# 可简写为
# [root@localhost ~]# nerdctl run -it ubuntu# 容器状态为Exited
[root@localhost ~]# nerdctl container ls
CONTAINER ID    IMAGE    COMMAND    CREATED    STATUS    PORTS    NAMES
[root@localhost ~]# nerdctl container ls -a
CONTAINER ID    IMAGE                              COMMAND        CREATED               STATUS                           PORTS    NAMES
440e564c529b    docker.io/library/ubuntu:latest    "/bin/bash"    About a minute ago    Exited (0) About a minute ago             ubuntu-440e5
rm

作用:删除容器。
示例:

[root@localhost ~]# nerdctl container rm 440e564c529b
440e564c529b
[root@localhost ~]# nerdctl container ls -a
CONTAINER ID    IMAGE    COMMAND    CREATED    STATUS    PORTS    NAMES
prune

作用:删除所有未运行的容器。
示例:

# 准备环境
[root@localhost ~]# nerdctl container run ubuntu
[root@localhost ~]# nerdctl container run ubuntu
[root@localhost ~]# nerdctl container ls -a
CONTAINER ID    IMAGE                              COMMAND        CREATED           STATUS                       PORTS    NAMES
58310e6b4916    docker.io/library/ubuntu:latest    "/bin/bash"    7 seconds ago     Exited (0) 7 seconds ago              ubuntu-58310
f09c6240a387    docker.io/library/ubuntu:latest    "/bin/bash"    12 seconds ago    Exited (0) 11 seconds ago             ubuntu-f09c6# 执行
[root@localhost ~]# nerdctl container prune --force
Deleted Containers:
58310e6b4916bf8e69e04e226c0ad801edd5fa964e4e6330caeec23cea0390c6
f09c6240a38799bc7e2c3892de11cd23f6c7be09a7cef6f036d0e444d471a799
rename

作用:重命名容器。
示例:

[root@localhost ~]# nerdctl container run --name ubuntu-1 ubuntu
[root@localhost ~]# nerdctl container ls -a
CONTAINER ID    IMAGE                              COMMAND        CREATED           STATUS                       PORTS    NAMES
9ad940d0bb0d    docker.io/library/ubuntu:latest    "/bin/bash"    13 seconds ago    Exited (0) 12 seconds ago             ubuntu-1
[root@localhost ~]# nerdctl container rename ubuntu-1 ubuntu
[root@localhost ~]# nerdctl container ls -a
CONTAINER ID    IMAGE                              COMMAND        CREATED           STATUS                       PORTS    NAMES
9ad940d0bb0d    docker.io/library/ubuntu:latest    "/bin/bash"    48 seconds ago    Exited (0) 47 seconds ago             ubuntu
[root@localhost ~]# nerdctl container rm ubuntu
ubuntu
stop 和 start

作用:停止和启动容器。
示例:

[root@localhost ~]# nerdctl container run -d --name nginx1 nginx
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
docker.io/library/nginx:latest:                                                   resolved       |++++++++++++++++++++++++++++++++++++++|
index-sha256:d5f28ef21aabddd098f3dbc21fe5b7a7d7a184720bc07da0b6c9b9820e97f25e:    done           |++++++++++++++++++++++++++++++++++++++|
manifest-sha256:27637a97e3d1d0518adc2a877b60db3779970f19474b6e586ddcbc2d5500e285: done           |++++++++++++++++++++++++++++++++++++++|
config-sha256:41f689c209100e6cadf3ce7fdd02035e90dbd1d586716bf8fc6ea55c365b2d81:   done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:6c50e4e0c4393a7c1dc665d7c0f5b717d184ead14a9a0cfd50acd7997fe5e70d:    done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:d107e437f7299a0db6425d4e37f44fa779f7917ecc8daf1e87128ee91b9ed3d3:    done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:cb497a329a815b4a2fe3b785e16e4589f3fe899a7d46834671125ef0b21e85ba:    done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:f1c4d397f477546f880aadb7faeeee8eaa1d40e3ded29e62b598f64acf629912:    done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:f72106e8650736e17bf673e22947b69f0074b76be40d5a728d0704a762d0d285:    done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:899c83fc198bc29704e0f259db984cde12bfbb7cb60363667b108955b05fdd7a:    done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:a785b80f5a670dcc22bd75e3ffd6463d1b27c37f53a799479bf8ac95d2330952:    done           |++++++++++++++++++++++++++++++++++++++|
elapsed: 2.8 s                                                                    total:  69.0 M (24.6 MiB/s)
57de7041db42088e8d17db3f82d7195c14e49b723647292d7dcea3661dc5d4ab
[root@localhost ~]# nerdctl container ls --format "{{.Names}} {{.Status}}"
nginx1 Up
[root@localhost ~]# nerdctl container stop nginx1
nginx1
[root@localhost ~]# nerdctl container ls --format "{{.Names}} {{.Status}}" -a
nginx1 Exited (0) 17 seconds ago
[root@localhost ~]# nerdctl container start nginx1
nginx1
[root@localhost ~]# nerdctl container ls --format "{{.Names}} {{.Status}}"
nginx1 Up
restart

作用:重启容器。
示例:

[root@localhost ~]# nerdctl container restart nginx1
nginx1
pause 和 unpause

作用:挂起和取消挂起容器。
示例:

[root@localhost ~]# nerdctl container pause nginx1
nginx1
[root@localhost ~]# nerdctl container ls --format "{{.Names}} {{.Status}}" -a
nginx1 Paused
[root@localhost ~]# nerdctl container unpause nginx1
nginx1
[root@localhost ~]# nerdctl container ls --format "{{.Names}} {{.Status}}" -a
nginx1 Up
kill

作用:给容器发信号,默认发KILL信号。
示例:

[root@localhost ~]# nerdctl container kill nginx1
57de7041db42088e8d17db3f82d7195c14e49b723647292d7dcea3661dc5d4ab
[root@localhost ~]# nerdctl container ls -a --format "{{.Names}} {{.Status}}"
nginx1 Exited (137) 9 seconds ago
exec

作用:在运行的容器内部执行命令。
示例:

[root@localhost ~]# nerdctl container start nginx1
nginx1
[root@localhost ~]# nerdctl container exec -it nginx1 bash
root@945c89b61aaf:/# exit
exit
cp

作用:将宿主机文件复制给容器。
示例:

[root@localhost ~]# nerdctl container cp /etc/hostname nginx1:
[root@localhost ~]# nerdctl container exec nginx1 ls hostname
hostname
inspect

作用:查看容器详细信息。
示例:

[root@localhost ~]# nerdctl container inspect nginx1[{"Id": "945c89b61aafc3475317e8801ad8526fdf337b038bfa315472e4c723bf5406f1","Created": "2025-08-02T14:07:36.213384887Z","Path": "/docker-entrypoint.sh","Args": ["nginx","-g","daemon off;"],"State": {"Status": "running","Running": true,"Paused": false,"Restarting": false,"Pid": 49359,"ExitCode": 0,"Error": "","FinishedAt": "0001-01-01T00:00:00Z"},"Image": "docker.io/library/nginx:latest","ResolvConfPath": "/var/lib/nerdctl/1935db59/containers/default/945c89b61aafc3475317e8801ad8526fdf337b038bfa315472e4c723bf5406f1/resolv.conf","HostnamePath": "/var/lib/nerdctl/1935db59/containers/default/945c89b61aafc3475317e8801ad8526fdf337b038bfa315472e4c723bf5406f1/hostname","LogPath": "/var/lib/nerdctl/1935db59/containers/default/945c89b61aafc3475317e8801ad8526fdf337b038bfa315472e4c723bf5406f1/945c89b61aafc3475317e8801ad8526fdf337b038bfa315472e4c723bf5406f1-json.log","Name": "nginx1","RestartCount": 0,"Driver": "overlayfs","Platform": "linux","AppArmorProfile": "","Mounts": null,"Config": {"Hostname": "945c89b61aaf","AttachStdin": false,"Labels": {"containerd.io/restart.explicitly-stopped": "false","io.containerd.image.config.stop-signal": "SIGQUIT","nerdctl/extraHosts": "null","nerdctl/hostname": "945c89b61aaf","nerdctl/log-uri": "binary:///usr/bin/nerdctl?_NERDCTL_INTERNAL_LOGGING=%2Fvar%2Flib%2Fnerdctl%2F1935db59","nerdctl/name": "nginx1","nerdctl/namespace": "default","nerdctl/networks": "[\"bridge\"]","nerdctl/platform": "linux/amd64","nerdctl/state-dir": "/var/lib/nerdctl/1935db59/containers/default/945c89b61aafc3475317e8801ad8526fdf337b038bfa315472e4c723bf5406f1"}},"NetworkSettings": {"GlobalIPv6Address": "","GlobalIPv6PrefixLen": 0,"IPAddress": "10.4.0.15","IPPrefixLen": 24,"MacAddress": "32:81:21:fb:b4:72","Networks": {"unknown-eth0": {"IPAddress": "10.4.0.15","IPPrefixLen": 24,"GlobalIPv6Address": "","GlobalIPv6PrefixLen": 0,"MacAddress": "32:81:21:fb:b4:72"}}}}
]
logs

作用:显示容器console终端内容。
示例:

[root@localhost ~]# nerdctl container logs nginx1
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: IPv6 listen already enabled
/docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2025/09/11 14:10:40 [notice] 1#1: using the "epoll" event method
2025/09/11 14:10:40 [notice] 1#1: nginx/1.29.0
2025/09/11 14:10:40 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14+deb12u1)
2025/09/11 14:10:40 [notice] 1#1: OS: Linux 4.18.0- 553.6.1.el8.x86_64
2025/09/11 14:10:40 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1024:1024
2025/09/11 14:10:40 [notice] 1#1: start worker processes
2025/09/11 14:10:40 [notice] 1#1: start worker process 22
2025/09/11 14:10:40 [notice] 1#1: start worker process 23
2025/09/11 14:10:40 [notice] 1#1: start worker process 24
2025/09/11 14:10:40 [notice] 1#1: start worker process 25
port

作用:显示宿主机和容器之间端口映射关系。
示例:

[root@localhost ~]# nerdctl container run --name nginx -d -p 8080:80 nginx
836013785affb9b2bc51cb74f8c876d956bc8d0796ee7b0b38110548b1442d97
[root@localhost ~]# nerdctl container port nginx
80/tcp -> 0.0.0.0:8080
commit

作用:将容器提交为镜像。
示例:

[root@localhost ~]# nerdctl commit nginx nginx_containerd
sha256:27c9864e1b4c79e6114ad0e71f971d0e78068e18c22bc0d5ba16329bbdb4e675
[root@localhost ~]# nerdctl images
REPOSITORY          TAG       IMAGE ID        CREATED          PLATFORM       SIZE         BLOB SIZE
nginx               latest    d5f28ef21aab    26 hours ago     linux/amd64    194.5 MiB    69.0 MiB
nginx_containerd    latest    15eeab920a0f    5 seconds ago    linux/amd64    194.5 MiB    69.0 MiB
ubuntu              latest    353675e2a41b    6 days ago       linux/amd64    81.1 MiB     28.4 MiB
nerdctl管理网络

Containerd(搭配 nerdctl)搞网络,和 Docker 的思路很像 —— 所有网络接口都是 “虚拟的”,不是真的插网线的物理接口。

当你用 nerdctl 建容器时,它会先在主机里搭个叫 “bridge” 的 “虚拟网桥”(就像家里的路由器),还给这网桥配了个叫 “nerdctl0” 的 “内部接口”(相当于路由器的 “LAN 口”)。接着,它会在主机和容器里各建一个 “配对的虚拟接口”(这对接口叫 vethpair,像一根 “虚拟网线”),把两者连起来。最后,Containerd 还会提前给 “nerdctl0” 设好固定的 IP 和子网掩码 —— 这样一来,主机和容器就像连在同一个路由器下的设备,能通过这个 “虚拟网桥” 顺畅通信了。

示例:

[root@localhost ~]# nerdctl run -d busybox -- sleep infinity
docker.io/library/busybox:latest:                                                 resolved       |++++++++++++++++++++++++++++++++++++++|
index-sha256:d82f458899c9696cb26a7c02d5568f81c8c8223f8661bb2a7988b269c8b9051e:    done           |++++++++++++++++++++++++++++++++++++++|
manifest-sha256:182014572d8981d8323fe9944876f63b39694e16ce08ae6296e97686c52b150c: done           |++++++++++++++++++++++++++++++++++++++|
config-sha256:0ed463b26daee791b094dc3fff25edb3e79f153d37d274e5c2936923c38dac2b:   done           |++++++++++++++++++++++++++++++++++++++|
layer-sha256:80bfbb8a41a2b27d93763e96f5bdccb8ca289387946e406e6f24053f6a8e8494:    done           |++++++++++++++++++++++++++++++++++++++|
elapsed: 4.6 s                                                                    total:  2.1 Mi (471.9 KiB/s)
ba554106edbbb4a99246b3b7a9b390be8bdb5cd5138d270fc7af470c32b61177
[root@localhost ~]# nerdctl container ls
CONTAINER ID    IMAGE                               COMMAND                   CREATED           STATUS    PORTS                   NAMES
836013785aff    docker.io/library/nginx:latest      "/docker-entrypoint.…"    12 minutes ago    Up        0.0.0.0:8080->80/tcp    nginx
ba554106edbb    docker.io/library/busybox:latest    "sleep infinity"          2 minutes ago     Up                                busybox-ba554
[root@localhost ~]# nerdctl exec busybox-ba554 -- ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::1/128 scope hostvalid_lft forever preferred_lft forever
2: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueuelink/ether 72:83:6f:02:14:1a brd ff:ff:ff:ff:ff:ffinet 10.4.0.3/24 brd 10.4.0.255 scope global eth0valid_lft forever preferred_lft foreverinet6 fe80::7083:6fff:fe02:141a/64 scope linkvalid_lft forever preferred_lft forever

容器内看到的网卡名: 2: eth0@if7 ,@if7代表对端是7号网卡。

[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::1/128 scope hostvalid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000link/ether 00:0c:29:d8:d2:22 brd ff:ff:ff:ff:ff:ffaltname enp3s0inet 192.168.108.135/24 brd 192.168.108.255 scope global dynamic noprefixroute ens160valid_lft 1495sec preferred_lft 1495secinet6 fe80::20c:29ff:fed8:d222/64 scope link noprefixroutevalid_lft forever preferred_lft forever
3: nerdctl0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000link/ether f2:b3:39:3f:c0:f5 brd ff:ff:ff:ff:ff:ffinet 10.4.0.1/24 brd 10.4.0.255 scope global nerdctl0valid_lft forever preferred_lft foreverinet6 fe80::4809:cfff:fe43:508e/64 scope linkvalid_lft forever preferred_lft forever
6: veth533d2c66@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master nerdctl0 state UP group defaultlink/ether f2:b3:39:3f:c0:f5 brd ff:ff:ff:ff:ff:ff link-netnsid 0inet6 fe80::f0b3:39ff:fe3f:c0f5/64 scope linkvalid_lft forever preferred_lft forever
7: vethc16109f5@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master nerdctl0 state UP group defaultlink/ether f2:c9:3c:1c:bc:db brd ff:ff:ff:ff:ff:ff link-netnsid 1inet6 fe80::f0c9:3cff:fe1c:bcdb/64 scope linkvalid_lft forever preferred_lft forever

对应容器主机的网卡: 7: vethc16109f5@if2 , @if2 代表对端容器内对应2号网卡。

示例:

[root@localhost ~]# nerdctl network ls
NETWORK ID      NAME      FILE
17f29b073143    bridge    /etc/cni/net.d/nerdctl-bridge.conflisthostnone
[root@localhost ~]# nerdctl network inspect bridge
[{"Name": "bridge","Id": "17f29b073143d8cd97b5bbe492bdeffec1c5fee55cc1fe2112c8b9335f8b6121","IPAM": {"Config": [{"Subnet": "10.4.0.0/24","Gateway": "10.4.0.1"}]},"Labels": {"nerdctl/default-network": "true"}}
]# 主机中nerdctl0就是容器的网关
[root@localhost ~]# ip addr show nerdctl0
3: nerdctl0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000link/ether f2:b3:39:3f:c0:f5 brd ff:ff:ff:ff:ff:ffinet 10.4.0.1/24 brd 10.4.0.255 scope global nerdctl0valid_lft forever preferred_lft foreverinet6 fe80::4809:cfff:fe43:508e/64 scope linkvalid_lft forever preferred_lft forever# 目前 Containerd 网桥是Linux网桥,用户可以使用 brctl show 命令查看网桥和端口连接信息。
[root@localhost ~]# brctl show
bridge name    bridge id          STP enabled    interfaces
nerdctl0       8000.3a1a93b7ead7  no             veth790d9140
nerdctl network命令使用帮助
[root@localhost ~]# nerdctl network --help
Manage networksUsage: nerdctl network [flags]Commands:create   Create a networkinspect  Display detailed information on one or more networksls       List networksprune    Remove all unused networksrm       Remove one or more networksFlags:-h, --help   help for networkSee also 'nerdctl --help' for the global flags such as '--namespace', '--snapshotter', and '--cgroup-manager'.
nerdctl 管理存储

nerdctl volume 命令使用帮助

[root@localhost ~]# nerdctl volume --help
Manage volumesUsage: nerdctl volume [flags]Commands:create   Create a volumeinspect  Display detailed information on one or more volumesls       List volumesprune    Remove all unused local volumesrm       Remove one or more volumesFlags:-h, --help   help for volumeSee also 'nerdctl --help' for the global flags such as '--namespace', '--snapshotter', and '--cgroup-manager'.

nerdctl 命令创建容器的时候,可以使用 -v 选项将本地目录挂载给容器实现数据持久化。

示例:

# 在宿主机上创建/data目录
[root@localhost ~]# mkdir /data# 运行一个busybox容器,将宿主机的/data目录挂载到容器内的/data目录
# -d: 后台运行容器
# -v /data:/data: 挂载宿主机的/data目录到容器内的/data目录
# -- sleep infinity: 让容器保持运行状态
[root@localhost ~]# nerdctl run -d -v /data:/data busybox -- sleep infinity
d00a1646169a199e3038851f86b82bff03ac2db6ffd8ea3e875789d2a6d1a000  # 容器ID# 在宿主机的/data目录下创建文件f1
[root@localhost ~]# touch /data/f1# 在容器内执行ls命令查看/data目录内容
# 可以看到宿主机创建的f1文件在容器内也能看到,说明目录挂载成功
[root@localhost ~]# nerdctl exec busybox-d00a1 -- ls /data
f1

nerdctl 命令创建容器的时候,也可以使用 -v 选项指定volume。

# 直接使用容器内目录/data,会自动生成对应的宿主机目录
[root@localhost ~]# nerdctl run -d -v /data busybox -- sleep infinity
29c94622886a219c93b5f6cd1c1ab190f998c66e3b4cbce75437507803b82eea  # 容器ID# 在容器内的/data目录下创建文件f2
[root@localhost ~]# nerdctl exec busybox-29c94 -- touch /data/f2# 指定宿主机卷名为data,并挂载到容器内/data目录
[root@localhost ~]# nerdctl run -d -v data:/data busybox -- sleep infinity
1b1fc00e88471a5abd8787bae438ab8d5ab08f4ec4fa073805407f9fffe2fe73  # 容器ID# 在该容器内的/data目录下创建文件f3
[root@localhost ~]# nerdctl exec busybox-1b1fc -- touch /data/f3# 查看所有卷信息
[root@localhost ~]# nerdctl volume ls
VOLUME NAME                                       DIRECTORY 
0c70033c26bcf456d9a0dc3f7dfe723f232e48dee2c8898bf987f8aeebacc1c7  /var/lib/nerdctl/1935db59/volumes/default/0c70033c26bcf456d9a0dc3f7dfe723f232e48dee2c8898bf987f8aeebacc1c7/_data  # 自动生成的卷名及路径
data                                              /var/lib/nerdctl/1935db59/volumes/default/data/_data  # 指定的卷名data及路径# 查看自动生成卷的目录内容,包含之前创建的f2
[root@localhost ~]# ls /var/lib/nerdctl/1935db59/volumes/default/0c70033c26bcf456d9a0dc3f7dfe723f232e48dee2c8898bf987f8aeebacc1c7/_data
f2# 查看指定卷data的目录内容,包含之前创建的f3
[root@localhost ~]# ls /var/lib/nerdctl/1935db59/volumes/default/data/_data
f3
nerdctl 管理命名空间
[root@localhost ~]# nerdctl namespace
Unrelated to Linux namespaces and Kubernetes namespaces
Usage:  nerdctl namespace [flags]
Aliases:namespace, ns
Commands:create      Create a new namespaceinspect     Display detailed information on one or more namespaces.ls          List containerd namespacesremove      Remove one or more namespacesupdate      Update labels for a namespace
Flags:-h, --help   help for namespace
See also 'nerdctl --help' for the global flags such as '--namespace', '--snapshotter', and '--cgroup-manager'.

示例:

# 执行nerdctl命令namespace ls命令,列出所有containerd命名空间及其相关信息
# 输出结果的表头说明:
# NAME:命名空间名称
# CONTAINERS:该命名空间中的容器数量
# IMAGES:该命名空间中的镜像数量
# VOLUMES:该命名空间中的卷数量
# LABELS:该命名空间的标签信息
[root@localhost ~]# nerdctl namespace ls
NAME      CONTAINERS   IMAGES   VOLUMES   LABELS
default   10           4        2          # 这是默认命名空间,包含10个容器、4个镜像和2个卷,没有标签

七、crictl 实践

crictl 命令介绍

crictl 命令是遵循 CRI 接口规范的一个命令行工具,通常用它来检查和管理 kubelet 节点上的容器运行时和镜像。
在kubernetes集群环境中,当我们执行 kubectl 命令式, kubelet 代理会自动调用crictl命令管理镜像和容器。
手动执行 crictl 命令时,一般用于查看镜像和容器。

crictl 命令安装
配置kubernetes源:
[root@localhost ~]# cat <<EOF | tee /etc/yum.repos.d/kubernetes.repo
> [kubernetes]
> name=Kubernetes
> baseurl=https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.30/rpm/
> enabled=1
> gpgcheck=1
> gpgkey=https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.30/rpm/repodata/repomd.xml.key
> EOF
安装CRI命令
[root@localhost ~]# yum install -y cri-tools
crictl 命令配置

使用 crictl 命令之前,需要先配置 /etc/crictl.yaml
**示例:**配置crictl后端运行时使用containerd。

[root@localhost ~]# vim /etc/crictl.yaml
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 5
debug: false

也可以通过命令进行设置:

[root@localhost ~]# crictl config runtime-endpoint unix:///run/containerd/containerd.sock
[root@localhost ~]# crictl config image-endpoint unix:///run/containerd/containerd.sock

更多命令操作,可以直接在命令行输入命令查看帮助。

[root@localhost ~]# crictl config --help
NAME:crictl config - Get and set crictl client configuration optionsUSAGE:crictl config [command options] [<crictl options>]EXAMPLE:crictl config --set debug=trueCRICTL OPTIONS:runtime-endpoint:      Container runtime endpointimage-endpoint:        Image endpointtimeout:               Timeout of connecting to server (default: 2s)debug:                 Enable debug output (default: false)pull-image-on-create:  Enable pulling image on create requests (default: false)disable-pull-on-run:   Disable pulling image on run requests (default: false)OPTIONS:--get value                  show the option value--list                       show all option value (default: false)--set value [ --set value ]  set option (can specify multiple or separate values with commas: opt1=val1,opt2=val2)--help, -h                   show help
crictl 命令实践
帮助信息
[root@localhost ~]# crictl
NAME:crictl - client for CRIUSAGE:crictl [global options] command [command options]VERSION:v1.30.1COMMANDS:attach              Attach to a running containercreate              Create a new containerexec                Run a command in a running containerversion             Display runtime version informationimages, image, img  List imagesinspect             Display the status of one or more containersinspecti            Return the status of one or more imagesimagefsinfo         Return image filesystem infoinspectp            Display the status of one or more podslogs                Fetch the logs of a containerport-forward        Forward local port to a podps                  List containerspull                Pull an image from a registryrun                 Run a new container inside a sandboxrunp                Run a new podrm                  Remove one or more containersrmi                 Remove one or more imagesrmp                 Remove one or more podspods                List podsstart               Start one or more created containersinfo                Display information of the container runtimestop                Stop one or more running containersstopp               Stop one or more running podsupdate              Update one or more running containersconfig              Get and set crictl client configuration optionsstats               List container(s) resource usage statisticsstatsp              List pod statistics. Stats represent a structured API that will fulfill the Kubelet's /stats/summary endpoint.metricsp            List pod metrics. Metrics are unstructured key/value pairs gathered by CRI meant to replace cAdvisor's /metrics/cadvisor endpoint.completion          Output shell completion codecheckpoint          Checkpoint one or more running containersruntime-config      Retrieve the container runtime configurationevents, event       Stream the events of containershelp, h             Shows a list of commands or help for one commandGLOBAL OPTIONS:--config value, -c value                   Location of the client config file. If not specified and the default does not exist, the program's directory is searched as well (default: "/etc/crictl.yaml") [$CRI_CONFIG_FILE]--debug, -D                                Enable debug mode (default: false)--enable-tracing                           Enable OpenTelemetry tracing. (default: false)--image-endpoint value, -i value           Endpoint of CRI image manager service (default: uses 'runtime-endpoint' setting) [$IMAGE_SERVICE_ENDPOINT]--runtime-endpoint value, -r value         Endpoint of CRI container runtime service (default: uses in order the first successful one of [unix:///run/containerd/containerd.sock unix:///run/crio/crio.sock unix:///var/run/cri-dockerd.sock]). Default is now deprecated and the endpoint should be set instead. [$CONTAINER_RUNTIME_ENDPOINT]--timeout value, -t value                  Timeout of connecting to the server in seconds (e.g. 2s, 20s.). 0 or less is set to default (default: 2s)--tracing-endpoint value                   Address to which the gRPC tracing collector will send spans to. (default: "127.0.0.1:4317")--tracing-sampling-rate-per-million value  Number of samples to collect per million OpenTelemetry spans. Set to 1000000 or -1 to always sample. (default: -1)--help, -h                                 show help--version, -v                              print the version
镜像命令
# 列出所有本地镜像(三个命令效果相同)
images, image, img  # 示例:crictl images 会显示所有镜像的名称、标签、ID等信息# 从镜像仓库拉取镜像
pull  # 示例:crictl pull nginx:latest 会从仓库下载nginx最新版本镜像# 查看一个或多个镜像的详细信息
inspecti  # 示例:crictl inspecti nginx:latest 会显示镜像的元数据、配置等详情# 返回镜像文件系统的相关信息
imagefsinfo  # 可查看镜像占用的存储空间等文件系统层面的数据# 删除一个或多个本地镜像
rmi  # 示例:crictl rmi nginx:latest 会删除本地的nginx镜像

这些命令主要用于查看、获取、检查和删除 Kubernetes 节点上的容器镜像,是管理节点镜像资源的常用工具。

容器命令
# 列出容器(默认显示运行中的容器)
ps  # 示例:crictl ps 查看运行中的容器;crictl ps -a 查看所有容器(包括已停止的)# 创建一个新容器(仅创建不启动)
create  # 需指定镜像等参数,创建后需用 start 命令启动# 在沙箱(sandbox)中运行新容器(创建并启动)
run  # 一站式创建并启动容器,沙箱通常对应 Pod 级别的网络环境# 查看一个或多个容器的详细状态信息
inspect  # 示例:crictl inspect <容器ID> 查看容器配置、状态、挂载等详情# 显示容器运行时(如 containerd)的信息
info  # 可查看运行时版本、支持的特性、存储配置等# 连接到正在运行的容器(类似登录交互)
attach  # 示例:crictl attach <容器ID> 进入容器的标准输入输出# 在运行中的容器内执行命令
exec  # 示例:crictl exec <容器ID> ls /  在容器内执行 ls 命令# 获取容器的日志
logs  # 示例:crictl logs <容器ID> 查看容器输出的日志信息# 更新一个或多个运行中容器的配置
update  # 可调整资源限制等参数(如 CPU、内存上限)# 列出容器的资源使用统计信息
stats  # 实时显示容器的 CPU、内存、网络等资源占用情况# 为一个或多个运行中的容器创建检查点(快照)
checkpoint  # 可用于容器状态保存与恢复# 启动一个或多个已创建的容器(与 create 命令配合使用)
start  # 示例:crictl start <容器ID> 启动已创建但未运行的容器# 停止一个或多个运行中的容器
stop  # 示例:crictl stop <容器ID> 停止指定容器# 删除一个或多个容器(通常用于清理已停止的容器)
rm  # 示例:crictl rm <容器ID> 删除指定容器

这些命令覆盖了容器从创建、启动、管理到销毁的全生命周期操作,是在 Kubernetes 节点上直接操作容器的实用工具。

pod命令

Pod 是 Kubernetes 里最小的部署单元,你可以把它理解成一个 “迷你应用单元”。

# 列出节点上的所有 Pod
pods  # 示例:crictl pods 可查看当前节点上所有 Pod 的状态、ID、名称等信息# 运行一个新的 Pod
runp  # 需指定 Pod 配置等参数,直接创建并启动一个新 Pod# 查看一个或多个 Pod 的详细状态信息
inspectp  # 示例:crictl inspectp <podID> 可查看 Pod 的网络、容器列表、状态等详细配置# 列出 Pod 的资源使用统计信息
statsp  # 实时显示 Pod 的 CPU、内存、网络等资源占用情况,便于监控资源使用# 将本地端口转发到 Pod
port-forward  # 示例:crictl port-forward <podID> 8080:80 可将本地8080端口转发到Pod的80端口,方便本地访问Pod内服务# 停止一个或多个运行中的 Pod
stopp  # 示例:crictl stopp <podID> 停止指定的运行中 Pod# 删除一个或多个 Pod
rmp  # 示例:crictl rmp <podID> 删除指定的 Pod(通常用于清理已停止的 Pod)

这些命令主要用于在 Kubernetes 节点上直接操作 Pod,覆盖了 Pod 从创建、查看、监控到停止、删除的基本管理场景,适合在节点层面排查 Pod 相关问题。

其他命令
# 显示容器运行时的版本信息
version  # 示例:crictl version 会输出客户端(crictl)和服务端(如containerd)的版本、API版本等信息# 获取和设置crictl客户端的配置选项
config  # 示例:crictl config get server 查看当前连接的运行时服务地址;也可用于设置默认命名空间等配置# 输出shell自动补全代码
completion  # 可生成bash、zsh等shell的自动补全脚本,配置后输入crictl命令时按Tab键可自动补全,提高操作效率# 显示命令列表或单个命令的帮助信息
help, h  # 示例:crictl help 查看所有命令;crictl help pods 查看pods命令的具体用法

这些命令主要用于管理 crictl 工具本身的配置、查看版本信息,以及获取帮助,让用户能更方便地使用 crictl 进行操作。

命令行对照表
命令功能dockerpodmannerdctlctrcrictl
查看容器状态docker pspodman psnerdctl psctr task ls/ctr container lscrictl ps
查看镜像docker imagespodman imagesnerdctl imagesctr image lscrictl images
查看容器日志docker logspodman logsnerdctl logscrictl logs
查看容器信息docker inspectpodman inspectnerdctl inspectctr container infocrictl inspect
查看容器资源docker statspodman statsnerdctl statscrictl stats
运行新容器docker runpodman runnerdctl runctr run
修改镜像标签docker tagpodman tagnerdctl tagctr image tag
创建新容器docker createpodman createnerdctl createctr container createcrictl create
导入镜像docker loadpodman loadnerdctl loadctr image import
导出镜像docker savepodman savenerdctl savectr image export
删除容器docker rmpodman rmnerdctl rmctr container rmcrictl rm
删除镜像docker rmipodman rminerdctl rmictr image rmcrictl rmi
拉取镜像docker pullpodman pullnerdctl pullctr image pullcrictl pull
推送镜像docker pushpodman pushnerdctl pushctr image push
在容器内部执行命令docker execpodman execnerdctl execcrictl exec

如果您还对Docker比较怀旧的话,执行“alias docker=nerdctl”这样的命令后,您依然可以体验到与Docker相似的感觉。

nerdctl 和 crictl 都是用于管理和操作容器的命令行工具,但是它们在开发者、设计目的和功能上有所不同。

  1. nerdctl:

    • 开发者:由Docker的创始人之一,也是containerd项目的主要贡献者Akihiro Suda开发。
    • 设计目的:nerdctl是一个兼容Docker CLI的containerd CLI,意味着大部分Docker命令可以在nerdctl中运行。
    • 功能:
      1. 管理容器的生命周期,如创建、运行、停止和删除容器。
      2. 支持镜像管理(拉取、推送、删除、查看等)。
      3. 支持网络管理(创建、查看、删除网络等)。
      4. 支持卷管理(创建、查看、删除数据卷等)。
  2. crictl:

    • 开发者:由Kubernetes项目社区开发。
    • 设计目的:crictl是一个命令行接口,用于与任何实现了Kubernetes容器运行时接口(CRI)的容器运行时进行交互,例如containerd、CRI-O等。
    • 功能:
      1. 主要用于Kubernetes节点层面的调试,从Kubernetes API Server的角度检查和理解容器运行时的行为。
      2. 允许用户直接与容器运行时交互,实现容器生命周期管理(创建、启动、停止、删除容器等)。
      3. 支持镜像管理(拉取、查看、删除镜像等)。
      4. 支持Pod相关操作(查看Pod状态、资源占用等),适配Kubernetes的Pod管理逻辑。

总的来说,二者主要区别在于他们的使用场景和目标用户并不完全相同。nerdctl更适合需要Docker CLI兼容性的用户,而crictl则更适合需要调试和理解Kubernetes CRI容器运行时行为的用户。

http://www.dtcms.com/a/457809.html

相关文章:

  • 大数据毕业设计-基于大数据的BOSS直聘岗位招聘数据可视化分析系统(高分计算机毕业设计选题·定制开发·真正大数据·机器学习毕业设计)
  • 网站开发建设培训网站策划书预期风险
  • aspnet网站模板人人秀h5页面制作软件
  • mysql数据库学习之高级进阶(七)
  • 做网站的书知乎建地方的网站前景
  • 数字化转型:概念性名词浅谈(第六十七讲)
  • Arduino开发ESP32连接手机热点【适合新手】
  • 网站搭建策划书网站备案流程审核单
  • 网站源码交易平台郑州阿里巴巴网站建设
  • 教育培训手机网站模板下载电脑端网站和手机网站区别
  • 集成热部署
  • 【代码随想录算法训练营——Day28】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树
  • 河北建设执业资格注册中心网站响应式网站 软件
  • tuchuang_共享文件_图片_取消_删除
  • 基因组组装:1. Hifiasm 组装参考基因组
  • 网站制作设计专业公司网络营销个人总结
  • 力扣2779. 数组的最大美丽值
  • 深圳做分销网站北京搭建工厂
  • 甘肃省建设厅执业资格注册中心网站通知网站开发三个月能学会吗
  • 石家庄手机网站建设装饰装修网站大全
  • 鼎锋优配股票杠杆交易市场赣锋锂业涨超6%,创两年多新高
  • 网络服务投诉平台商丘seo快速排名
  • 自适应网站欣赏wordpress主题超限
  • TODO 分类任务指标计算和展示 准确率 F1 Recall
  • 网站分辨率做96是否会更好织梦做双语网站
  • 贪心:火烧赤壁
  • 公司网站建设的环境分析城乡建设厅官方网站办事大厅
  • 深度学习基础:从原理到实践——附录A:PyTorch 深度学习框架基础(下)
  • 网站 二级分类品牌创意网站建设徕卡e
  • 做网站设计师庐江网站制作