如何在不使用 ELB 的情况下为 EC2 实例实施自定义健康检查?

How to implement custom health checks for EC2 instances without using an ELB?

场景:

我想添加一个简单的健康检查,以确保 Web 服务器仍然响应,因此如果 docker 容器出现故障,Auto Scaling 组可以替换该实例。

据我所知,只有ELB支持自定义健康检查。由于我不需要 ELB,我想知道 运行 使用 cron 作业在 EC2 实例中进行健康检查是否有意义。如果网络服务器没有响应(本地),它可以像这样设置健康状态:

export INSTANCE=$(curl http://169.254.169.254/latest/meta-data/instance-id)
export AWS_DEFAULT_REGION=$(curl http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\" '{print }')
aws autoscaling set-instance-health --instance-id $INSTANCE --health-status Unhealthy

我想,它应该可以工作,但看起来有点复杂。 是否有更好的方法来实现自定义健康检查(不使用 ELB)?

2017 年,没有 AWS 的直接支持,只有 API 来设置 EC2 实例的健康状况。因此,问题中描述的技术是推荐的方式:

  • 实施自定义健康检查(可以是 shell 脚本或您选择的任何内容)并定期 运行 它(通过 cron 或您选择的任何内容)
  • 使用autoscaling set-instance-health API将结果传达给自动缩放组

AWS documentation on custom health checks:

If you have custom health checks, you can send the information from your health checks to Auto Scaling so that Auto Scaling can use this information. For example, if you determine that an instance is not functioning as expected, you can set the health status of the instance to Unhealthy. The next time that Auto Scaling performs a health check on the instance, it will determine that the instance is unhealthy and then launch a replacement instance.

Use the following set-instance-health command to set the health state of the specified instance to Unhealthy:

aws autoscaling set-instance-health --instance-id i-123abc45d –-health-status Unhealthy