You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS CDK目标组注册端口异常:健康检查端口为何覆盖转发端口?

问题原因与解决方案

原因分析

当你将ECS Ec2Service直接传入ApplicationTargetGroup的targets参数时,CDK默认会将TargetGroup的目标类型设置为IP(对应容器的私有IP),并自动使用任务定义中容器暴露的端口作为目标转发端口。这就导致注册目标的端口被设置为容器端口(从结果看你的容器端口是8080),而非你在TargetGroup构造函数中指定的80端口。你配置的健康检查端口8080仅用于健康检查流程,并非目标端口被修改的直接原因。

正确配置方式

要实现ALB->80->TargetGroup->80->EC2实例的转发逻辑,同时用8080端口执行健康检查,需要调整TargetGroup的配置,明确指定目标类型为实例(INSTANCE),并将ECS服务关联到该TargetGroup:

修改后的CDK代码如下:

// 创建ECS Service(原代码不变)
const ecsAdminService = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  serviceName: `myapp-${targetEnv}-service`,
  enableExecuteCommand:true,
  securityGroups: [adminServiceSg],
  vpcSubnets:{subnetType: ec2.SubnetType.PUBLIC },
})

// 引用已有ALB监听器(原代码不变)
const securityGroup = ec2.SecurityGroup.fromSecurityGroupId(this, "MyAlbSecGroup", "sg-079b53d9492ab0f6c")
const listenerArn =   "arn:aws:elasticloadbalancing:ap-northeast-1:678100111111:listener/app/main-lb/a3de82872d7d166c/e247d72a4b0df559";
const existingListener = elb.ApplicationListener.fromApplicationListenerAttributes(this, "SharedListener", {
     listenerArn,
     securityGroup
});

// 创建目标类型为INSTANCE的TargetGroup,指定转发端口为80
const targetGroup = new elb.ApplicationTargetGroup(this,"myapp-ECS", {
     targetGroupName:`myapp-${targetEnv}-tg`,
     port: 80,
     targetType: elb.TargetType.INSTANCE, // 关键:明确目标为EC2实例
     vpc: cluster.vpc,
});

// 将ECS服务关联到TargetGroup
ecsAdminService.attachToApplicationTargetGroup(targetGroup);

// 添加监听器路由规则(原代码不变)
existingListener.addTargetGroups("myapp-tg",{
     priority:5,
     conditions:[
       elb.ListenerCondition.hostHeaders(['myapp.example.jp'])
     ],
     targetGroups:[targetGroup]
})

// 配置健康检查使用8080端口(原代码不变)
targetGroup.configureHealthCheck({
     path: "/",
     port: "8080" 
})

额外注意事项

  • 确保EC2实例的安全组(adminServiceSg)允许ALB的安全组访问80端口(转发流量)和8080端口(健康检查)
  • 确认EC2实例上的80端口有对应服务监听,8080端口存在可访问的健康检查端点

内容的提问来源于stack exchange,提问作者whitebear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:07:03