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

ECS中Redis的NLB健康检查始终失败问题求助

解决NLB健康检查Redis失败的思路

1. 修正Redis监听地址

官方Redis镜像默认配置为绑定127.0.0.1,仅接受容器内部连接。NLB的健康检查流量来自VPC内的NLB节点,属于容器外部请求,因此会被拒绝。

解决代码:
在容器定义中添加启动命令,让Redis绑定0.0.0.0以允许所有IP访问:

const qmmRedisContainer = qmmRedisTaskDefinition.addContainer('qmm_redis_NLB', {
    image: ecs.ContainerImage.fromRegistry('redis:6.0-alpine'),
    containerName: 'qmm_redis_NLB',
    portMappings: [{ containerPort: 6379, name: 'redis-port' }],
    // 添加启动命令,修改监听地址
    command: ["redis-server", "--bind", "0.0.0.0"],
    healthCheck: {
        command: ["CMD", "redis-cli", "-h", "localhost", "-p", "6379", "ping"],
        interval: cdk.Duration.seconds(25),
        timeout: cdk.Duration.seconds(25),
        retries: 5
    },
    logging: ecs.LogDriver.awsLogs({streamPrefix: 'qmm_redis_NLB'}),
})

2. 配置安全组允许NLB流量

默认安全组规则可能未放开NLB到Fargate任务的6379端口访问,需要手动添加规则:

解决代码:

// 创建服务专用安全组
const redisServiceSg = new ec2.SecurityGroup(this, 'RedisServiceSg', {
    vpc: props.vpc,
    allowAllOutbound: true,
})

// 允许NLB安全组访问Redis端口
redisServiceSg.addIngressRule(
    ec2.Peer.securityGroupId(qmmRedisServiceNLB.loadBalancer.securityGroup!.securityGroupId),
    ec2.Port.tcp(6379)
)

// 创建服务时指定安全组
const qmmRedisServiceNLB = new ecs_patterns.NetworkLoadBalancedFargateService(this, 'qmmRedisServiceNLB', {
    serviceName: 'qmmRedisServiceNLB',
    cluster: props.cluster,
    desiredCount: 1,
    taskDefinition: qmmRedisTaskDefinition,
    cloudMapOptions: {
        cloudMapNamespace: props.cluster.defaultCloudMapNamespace,
        name: 'qmm_redis_NLB',
        containerPort: 6379
    },
    listenerPort: 6379,
    securityGroups: [redisServiceSg]
})

3. 调整NLB目标组健康检查配置

默认健康检查参数可能不匹配Redis的响应特性,需手动优化:

解决代码:

// 修改目标组健康检查配置
qmmRedisServiceNLB.targetGroup.configureHealthCheck({
    protocol: elbv2.Protocol.TCP,
    port: '6379',
    interval: cdk.Duration.seconds(10),
    timeout: cdk.Duration.seconds(5),
    healthyThresholdCount: 2,
    unhealthyThresholdCount: 2
})

4. 区分两类健康检查

你配置的容器healthCheck是ECS任务自身的健康检查,用于判断容器是否正常运行;而NLB的健康检查是目标组层面的检查,用于决定是否将流量转发至该任务。两者独立,需确保各自配置正确。

额外注意事项

  • 若Redis设置了密码,NLB四层TCP健康检查无需密码;如果使用应用层检查(如redis-cli ping),则需在命令中加入密码参数。
  • 确认Fargate任务所在子网与NLB的网络配置匹配:若NLB是互联网面向的,任务需部署在公有子网;若为内部NLB,任务需在可被NLB访问的私有子网。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:44:58