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

CDK Fargate 如何实现不同子域名映射到容器的不同端口

解决方案

你只需要补充两处配置即可实现需求:

  1. 补全监听器的api目标组配置,将匹配api.${domain}的流量转发到容器3001端口
  2. 新增Route53 A记录,将api.${domain}解析到你的负载均衡地址

修改后的完整代码片段

export class AwsStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const myHostedZone = new route53.HostedZone(this, "HostedZone", {
      zoneName: domain,
    });

    const certificate = new acm.Certificate(this, "Certificate", {
      domainName: `*.${domain}`,
      validation: acm.CertificateValidation.fromDns(myHostedZone),
    });

    const image = new ecr.DockerImageAsset(this, "Image", { directory: "." });

    const vpc = new ec2.Vpc(this, "ApplicationVpc", { maxAzs: 2 });

    const cluster = new ecs.Cluster(this, "Cluster", {
      clusterName: "Cluster",
      vpc,
    });

    const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef");
    taskDefinition.addContainer("DefaultContainer", {
      image: ecs.ContainerImage.fromDockerImageAsset(image),
      portMappings: [
        { containerPort: 3000, hostPort: 3000 },
        { containerPort: 3001, hostPort: 3001 },
      ],
    });

    const service = new ecsPatterns.ApplicationLoadBalancedFargateService(this, "Service", {
      cluster,
      publicLoadBalancer: true,
      taskDefinition,
      certificate,
      // 显式指定默认规则转发到3000端口,确保兜底规则符合预期
      targetProtocol: elb.ApplicationProtocol.HTTP,
      listenerPort: 443,
    });

    // 原有HTTP跳HTTPS的配置保留
    service.loadBalancer.addRedirect()

    // 补全api子域名的转发规则,指向3001端口
    service.listener.addTargets("api", {
      priority: 10,
      conditions: [elb.ListenerCondition.hostHeaders([`api.${domain}`])],
      targets: [service.service],
      port: 3001,
      protocol: elb.ApplicationProtocol.HTTP,
      // 按需配置健康检查,不需要可以直接删掉
      healthCheck: {
        path: "/",
        healthyHttpCodes: "200",
      }
    });

    // 新增api子域名的Route53解析记录
    new route53.ARecord(this, "ApiARecord", {
      zone: myHostedZone,
      recordName: `api.${domain}`,
      target: route53.RecordTarget.fromAlias(new targets.LoadBalancerTarget(service.loadBalancer)),
    });
  }
}

配置说明

  • 默认兜底规则:ApplicationLoadBalancedFargateService创建时会自动生成监听器的默认转发规则,默认按照portMappings的第一个端口3000转发,刚好符合其余所有域名走3000端口的需求,也可以通过显式配置targetGroup相关参数进一步明确规则。
  • 优先级逻辑:你配置的priority:10小于默认规则的优先级(默认规则优先级为全局最低),所以请求会优先匹配api子域名的规则,命中后转发到3001端口,没有命中的走默认规则到3000端口。
  • 你已经申请了泛域名证书,天然覆盖api.${domain},不需要额外申请新证书。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:18:02