资源限制

如果容器尝试使用的内存多于系统可用的内存,则可能会遇到内存不足异常(OOME),并且容器或Docker守护程序可能会被内核OOM杀手杀死。要防止这种情况发生,请确保您的应用程序在具有足够内存的主机上运行.

您可以通过以下方式降低OOME导致系统不稳定的风险:

  • 在将应用程序投入生产之前,请执行测试以了解应用程序的内存要求
  • 确保您的应用程序仅在具有足够资源的主机上运行
  • 限制容器可以使用的内存量,如下所述
-m, --memory=
--cpus=<value>


  • 在Docker主机上配置交换时要小心。交换比内存更慢且性能更低,但可以提供缓冲以防止系统内存耗尽
  • 考虑将容器转换为服务,并使用服务级别约束和节点标签来确保应用程序仅在具有足够内存的主机上运行
--reserve-memory或--reserve-cpu
--constraint node.labels.region==east


compose模板示例:

version: '3'
services:
redis:
image: redis:alpine
deploy:
resources:
limits:
cpus: '0.50'
memory: 50M
reservations:
cpus: '0.25'
memory: 20M


健康检查

compose模板示例:

healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 40s
test: ["CMD-SHELL", "curl -f http://localhost || exit 1"]
等价于:
test: curl -f https://localhost || exit 1
# 禁用健康检查
healthcheck:
disable: true