Terraform配置AWS ALB健康检查失败报502错误求助
ALB健康检查失败返回502错误的排查与修复
问题场景
使用AWS+Terraform搭建VPC环境,两个可用区的私有子网各部署一台搭载Web服务的EC2实例,配置NAT Gateway和弹性IP,目标通过公网ALB转发请求,但ALB健康检查失败,返回502错误。已通过堡垒主机验证EC2实例可正常访问互联网。
配置中的关键问题及修复方案
1. 私有子网路由表配置冲突
你的私有路由表aws_route_table.private中存在两条默认路由(0.0.0.0/0),分别指向Internet Gateway和NAT Gateway,这会导致路由优先级冲突,私有子网的出站流量应仅通过NAT Gateway转发,不能直接走IGW。
修复后的路由表代码:
resource "aws_route_table" "private" { vpc_id = aws_vpc.main.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_nat_gateway.main.id } tags = { Name = "my-private-route-table" } }
2. 目标组健康检查规则缺失
当前aws_alb_target_group.ec2未显式配置健康检查规则,默认会检查根路径/,若EC2上的Web服务未在该路径返回200-299状态码,会直接导致健康检查失败。需明确配置健康检查参数,同时确保Web服务正常响应。
补充健康检查配置的目标组代码:
resource "aws_alb_target_group" "ec2" { name = "my-alb-target-group" port = 80 protocol = "HTTP" vpc_id = aws_vpc.main.id # 显式配置健康检查规则 health_check { path = "/" # 根据Web服务实际访问路径调整 protocol = "HTTP" port = "traffic-port" interval = 30 timeout = 5 healthy_threshold = 2 unhealthy_threshold = 2 matcher = "200-299" # 期望的响应状态码范围 } tags = { Name = "my-alb-target-group" } }
3. 验证EC2实例上的Web服务状态
通过堡垒主机登录EC2实例,执行以下命令确认Web服务运行状态:
- 检查服务状态:
systemctl status httpd(Apache)或systemctl status nginx(Nginx) - 本地测试响应:
curl localhost:80,确认返回200状态码及正常内容
同时确认user_data.sh是否正确安装并启动Web服务,示例脚本内容参考:
#!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo "<h1>Hello from $(hostname -f)</h1>" > /var/www/html/index.html
4. 优化安全组规则(可选)
当前安全组允许所有IP访问EC2的80端口,更安全的做法是仅允许ALB所在安全组的流量访问:
resource "aws_security_group" "main" { name = "my-security-group" description = "Allow HTTP from ALB and SSH access" vpc_id = aws_vpc.main.id ingress { from_port = 80 to_port = 80 protocol = "tcp" security_groups = [aws_security_group.main.id] # 关联ALB使用的安全组 } ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } tags = { Name = "my-security-group" } }
修复步骤总结
- 修正私有子网路由表,移除指向IGW的默认路由
- 为目标组添加明确的健康检查配置
- 验证EC2上的Web服务是否正常运行
- 优化安全组规则(可选,提升环境安全性)
内容的提问来源于stack exchange,提问作者Zuxaw
相关产品推荐
相关产品推荐

