如何配置双活跃容器端口的ECS?健康检查与443转发问题
双端口ECS服务的健康检查与请求转发解决方案
1. 双端口健康检查配置(解决健康检查失败问题)
当前报错是因为目标组针对前端4200端口配置的/signin路径无法通过健康检查。由于后端5000端口已有现成健康检查点,推荐两种方案:
方案1:将健康检查指向后端端口(最简方案)
修改目标组的健康检查配置,指定访问后端5000端口的健康检查端点,同时保留前端请求转发逻辑:
listener.addTargets('ECS_ALB_ServerTarget', { port: 443, healthCheck: { path: "/your-backend-health-endpoint", // 替换为后端实际健康检查路径 enabled: true, protocol: elbv2.ApplicationProtocol.HTTP, port: '5000' // 明确健康检查访问容器的5000端口 }, protocol: elbv2.ApplicationProtocol.HTTP, targets: [service.loadBalancerTarget({ containerName: 'express-app-container', containerPort: 4200, })], }); // 可选:给ECS服务增加健康检查等待时间,避免启动初期误判 const service = new ecs.Ec2Service(this, 'express-app-service', { // ...其他配置 healthCheckGracePeriod: cdk.Duration.seconds(60), });
方案2:为双端口分别创建目标组(同时监控两个端口)
如果需要同时监控前后端服务状态,创建两个独立目标组,分别配置对应端口的健康检查,并通过路径规则分发请求:
// 后端5000端口目标组(用已有健康检查点) const backendTg = listener.addTargets('BackendTarget', { port: 443, healthCheck: { path: "/your-backend-health-endpoint", enabled: true, protocol: elbv2.ApplicationProtocol.HTTP, port: '5000' }, protocol: elbv2.ApplicationProtocol.HTTP, targets: [service.loadBalancerTarget({ containerName: 'express-app-container', containerPort: 5000, })], }); // 前端4200端口目标组(无HTTP健康端点则用TCP检查) const frontendTg = listener.addTargets('FrontendTarget', { port: 443, healthCheck: { protocol: elbv2.Protocol.TCP, // 前端无HTTP健康端点时用TCP检查端口是否存活 port: '4200', enabled: true }, protocol: elbv2.ApplicationProtocol.HTTP, targets: [service.loadBalancerTarget({ containerName: 'express-app-container', containerPort: 4200, })], }); // 配置路径规则,分发请求 listener.addAction('FrontendRoute', { priority: 10, conditions: [elbv2.ListenerCondition.pathPatterns(['/*'])], // 前端页面路径 action: elbv2.ListenerAction.forward([frontendTg]), }); listener.addAction('BackendRoute', { priority: 20, conditions: [elbv2.ListenerCondition.pathPatterns(['/api/*'])], // 后端API路径 action: elbv2.ListenerAction.forward([backendTg]), });
2. 443请求转发至前端4200端口的配置
当前代码已实现基础转发,需注意以下细节:
- ALB的443监听器已配置SSL证书,会自动终止HTTPS连接,再以HTTP协议转发到容器的4200端口(对应代码中
protocol: elbv2.ApplicationProtocol.HTTP),无需额外配置。 - 如果需要区分前后端请求,按照方案2中的路径规则配置,将前端路径转发到4200端口目标组,后端API路径转发到5000端口。
必查注意事项
- 确认容器内前端服务确实在4200端口监听,ECS实例/任务的安全组允许ALB访问4200、5000端口。
- 健康检查路径必须能返回200状态码,TCP检查需确保端口处于监听状态。
- EC2模式下需保证主机端口(5000、4200)未被占用;Fargate模式可省略
hostPort配置,由平台自动映射。
内容的提问来源于stack exchange,提问作者Exorcismus
相关产品推荐
相关产品推荐

