求助:Terraform部署的AWS Fargate关联ALB出现连接超时问题
问题诊断与修复方案
以下是你的Terraform配置中导致负载均衡器访问超时的核心问题及修正:
1. 目标组端口与容器端口不匹配
你的容器监听8080端口,但负载均衡器的目标组aws_lb_target_group.websocket-server配置的端口是80。LB会将流量转发到目标组的80端口,但容器未在该端口监听,直接导致流量无法到达容器。
修正:
修改目标组端口为容器实际监听的8080:
resource "aws_lb_target_group" "websocket-server" { name = "websocket-server" port = 8080 # 改为容器监听端口 protocol = "HTTP" vpc_id = aws_vpc.main.id target_type = "ip" health_check { enabled = true healthy_threshold = 3 unhealthy_threshold = 3 timeout = 10 protocol = "HTTP" path = "/apis/websocket-server/health" interval = 100 # 移除引号,保持数字类型 matcher = "200" } depends_on = [aws_lb.main] }
2. 安全组缺少LB访问容器端口的规则
你的public安全组仅开放了80、443、22端口,但LB需要访问容器的8080端口来转发流量和执行健康检查,当前配置无相关放行规则,导致流量被拦截。
修正:
添加Ingress规则允许VPC内部流量访问8080端口:
resource "aws_security_group_rule" "public_in_container_port" { type = "ingress" from_port = 8080 to_port = 8080 protocol = "tcp" cidr_blocks = [aws_vpc.main.cidr_block] security_group_id = aws_security_group.public.id }
3. 公网子网未关联带IGW的路由表
你创建了Internet Gateway,但未配置公网路由表并关联到公网子网,会导致:
- 分配了公网IP的Fargate任务无法正常访问公网(如拉取ECR镜像)
- LB与ECS任务的私网通信受影响
修正:
创建公网路由表并关联到公网子网:
# 公网路由表 resource "aws_route_table" "public" { vpc_id = aws_vpc.main.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.main.id } tags = { Name = "Public Route Table" } } # 关联公网子网到路由表 resource "aws_route_table_association" "public" { subnet_id = aws_subnet.public.id route_table_id = aws_route_table.public.id } resource "aws_route_table_association" "public-backup" { subnet_id = aws_subnet.public-backup.id route_table_id = aws_route_table.public.id }
4. 私有安全组规则归属错误
你的aws_security_group_rule.private_in错误地将规则归属到public安全组,该规则应属于私有安全组:
修正:
resource "aws_security_group_rule" "private_in" { type = "ingress" from_port = 0 to_port = 65535 protocol = "-1" cidr_blocks = [aws_vpc.main.cidr_block] security_group_id = aws_security_group.private.id # 改为私有安全组ID }
验证步骤
- 应用修正后的配置:
terraform apply - 检查ECS任务状态及目标组健康检查是否变为
healthy - 再次访问负载均衡器URL或域名,确认连接正常
内容的提问来源于stack exchange,提问作者SebastianG
相关产品推荐
相关产品推荐

