资源限制
限制容器资源可以防止单个容器耗尽系统资源,提高系统稳定性。
内存限制
# 限制内存为 512MBdocker run -d --memory="512m" nginx
# 限制内存和 swapdocker run -d --memory="512m" --memory-swap="1g" nginx
# 禁用 swapdocker run -d --memory="512m" --memory-swap="512m" nginxCPU 限制
# 限制 CPU 使用率为 50%docker run -d --cpus="0.5" nginx
# 限制 CPU 核心数docker run -d --cpus="2" nginx
# 设置 CPU 权重docker run -d --cpu-shares=512 nginxDocker Compose 配置
services: web: image: nginx deploy: resources: limits: cpus: '0.5' memory: 512M reservations: cpus: '0.25' memory: 256M查看资源使用
# 查看所有容器资源使用docker stats
# 查看特定容器docker stats container_name
# 不实时更新docker stats --no-stream最佳实践
- ✅ 根据应用实际需求设置限制
- ✅ 监控资源使用情况
- ✅ 设置合理的内存限制防止 OOM
- ✅ 使用健康检查配合资源限制
- ✅ 在生产环境始终设置资源限制