DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 containerd 报错 failed to create shim task cannot allocate memory

分析 containerd 启动容器报 failed to create shim task cannot allocate memory 根因,提供 cgroup max_pids 与内核 pid_max 扩容方案。

问题现象

在 Kubernetes 节点上,大量 Pod 创建失败并停留在 ContainerCreating 状态。查看 containerd 系统日志或 kubectl describe pod 出现如下报错:

failed to create containerd task: failed to create shim task: OCI runtime create failed:
runc create failed: unable to start container process: error during container init:
unable to apply cgroup configuration: cannot allocate memory: unknown

或者提示:fork/exec /usr/bin/runc: cannot allocate memory,但宿主机查看 free -m 发现物理内存仍有数十 GB 空闲。

触发根因

  1. Linux 内核 kernel.pid_max 触顶:系统进程总数达到了系统级别上限,无法再执行 fork() 创建新的 shim 进程。
  2. systemd cgroup 的 TasksMax 限制:containerd.service 或 docker.service 被 systemd 强行限制了子进程/线程总数(DefaultTasksMax)。
  3. 内核内存碎片化或 vm.max_map_count 不足:特定场景下,虚拟内存区域分配耗尽。

诊断排查步骤

  1. 检查当前系统实际使用的 PID 数量与上限:
ps -eLf | wc -l
sysctl kernel.pid_max
  1. 检查 containerd 服务的 Tasks 限制与当前数值:
systemctl status containerd.service | grep Tasks

解决步骤与操作命令

步骤一:调高系统全局 pid_max 上限

修改 /etc/sysctl.d/99-kubernetes.conf:

sudo bash -c 'cat <<EOF >> /etc/sysctl.d/99-kubernetes.conf
kernel.pid_max = 4194304
vm.max_map_count = 262144
EOF'
sudo sysctl --system

步骤二:调整 systemd 对 containerd 的 TasksMax 限制

创建配置覆盖文件:

sudo mkdir -p /etc/systemd/system/containerd.service.d/
sudo bash -c 'cat <<EOF > /etc/systemd/system/containerd.service.d/override.conf
[Service]
TasksMax=infinity
LimitNPROC=infinity
LimitNOFILE=1048576
EOF'

步骤三:重载并重启 containerd 服务

sudo systemctl daemon-reload
sudo systemctl restart containerd

步骤四:验证容器正常启动

kubectl get pods -A | grep ContainerCreating

观察之前报错卡住的 Pod 顺利分配 Task 成功拉起为 Running。