Cgroups 限制资源

Cgroups 限制资源

什么是 Cgroups

Cgroups(Control Groups)是 Linux 内核功能,用于限制、记录和隔离进程组的资源使用。Docker 使用 cgroups 限制容器的 CPU、内存、磁盘 I/O 和网络带宽,防止某个容器耗尽宿主机所有资源。

Cgroups 管理的资源

资源类型 cgroups 控制器 Docker 参数
CPU cpu, cpuacct --cpus, --cpu-shares
内存 memory --memory, --memory-swap
磁盘 I/O blkio --io-* 参数
进程数 pids --pids-limit

CPU 资源限制

# 限制 CPU 核数(推荐)
docker run --cpus=1.5 nginx

# 绑定到特定 CPU 核
docker run --cpuset-cpus=0,2 nginx

# CPU 份额(相对权重,默认 1024)
docker run --cpu-shares=512 nginx
# 512 表示只有默认一半的 CPU 时间

内存限制

# 限制内存最大 256MB
docker run --memory=256m nginx

# 限制内存 + swap 最大 512MB
docker run --memory=256m --memory-swap=512m nginx

# 禁止使用 swap
docker run --memory=256m --memory-swap=256m nginx

# 软限制(尽力而为)
docker run --memory-reservation=128m nginx

磁盘 I/O 限制

# 限制写入 IOPS
docker run --device-write-iops=/dev/sda:100 nginx

# 限制读取带宽
docker run --device-read-bps=/dev/sda:5mb nginx

Docker Compose 中的资源限制

services:
  app:
    image: myapp
    deploy:
      resources:
        limits:            # 硬限制
          cpus: "0.5"
          memory: "256M"
        reservations:      # 软限制
          cpus: "0.25"
          memory: "128M"

查看 cgroups 配置

# 查看容器的 cgroups 配置
docker inspect container_name --format '{{json .HostConfig.Resources}}'

# 监控资源使用
docker stats

# 查看 cgroups 文件
cat /sys/fs/cgroup/memory/docker//memory.limit_in_bytes

默认值与风险

# 没有设置内存限制时风险很大
docker run nginx  # 可以 OOM 宿主机的内存

实际场景配置

services:
  web:
    image: nginx
    deploy:
      resources:
        limits:
          cpus: "0.5"
          memory: "256M"

  db:
    image: postgres:15
    deploy:
      resources:
        limits:
          cpus: "2.0"
          memory: "2G"

  worker:
    image: myworker
    deploy:
      resources:
        limits:
          cpus: "4.0"
          memory: "4G"

最佳实践

  1. 始终设置资源限制:防止”吵闹邻居”问题
  2. 设置适当的资源预留:保证关键服务能正常运行
  3. 使用 –cpus 而不是 –cpu-quota:语法更直观
  4. 监控资源使用:通过 docker stats 或外部监控工具
  5. 结合健康检查:资源不足时重启容器

Cgroups 保证了容器世界的”公平竞争”,没有它,一个失控的容器就能让整个系统瘫痪。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容