使用 CDK 使用正确的端口注册 Fargate 服务 ELB 目标?

Jay*_*ker 5 amazon-elb aws-fargate aws-cdk

我正在尝试添加 Fargate 服务作为应用程序负载均衡器目标,但它不断获取错误的容器端口。任务定义有两个容器:端口 8080 上的应用程序和端口 443 上的 nginx 反向代理。当我尝试通过 CDK 将它们连接在一起时,目标注册始终获取端口 8080。我似乎找不到方法或设置的 props 让我告诉 CDK 要使用哪个容器的端口。或者也许我是,但它忽略了它?我缺少什么?

这是一个精简的示例结构:

export class CdkFargateElbStack extends cdk.Stack {

  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

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

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

    const taskDef = new FargateTaskDefinition(this, 'TaskDefinition');

    const appContainer = new ContainerDefinition(this, 'AppContainer', {
      image: ContainerImage.fromRegistry(APP_IMAGE),
      taskDefinition: taskDef,
    });
    appContainer.addPortMappings({
      hostPort: 8080,
      containerPort: 8080
    });
    const proxyContainer = new ContainerDefinition(this, 'ProxyContainer', {
      image: ContainerImage.fromRegistry(PROXY_IMAGE),
      taskDefinition: taskDef,
    })
    proxyContainer.addPortMappings({
      hostPort: 443,
      containerPort: 443,
    });

    const service = new FargateService(this, 'Service', {
      cluster: cluster,
      taskDefinition: taskDef,
      assignPublicIp: true,
      desiredCount: 1,
      vpcSubnets: vpc.selectSubnets({
        subnetType: ec2.SubnetType.PUBLIC,
      }),
    });

    const alb = new elb.ApplicationLoadBalancer(this, 'LoadBalancer', {
      vpc: vpc,
      internetFacing: true,
      ipAddressType: elb.IpAddressType.IPV4,
      vpcSubnets: vpc.selectSubnets({
        subnetType: ec2.SubnetType.PUBLIC,
      })
    });

    const tg = new ApplicationTargetGroup(this, 'TargetGroup', {
      protocol: elb.ApplicationProtocol.HTTPS,
      port: 443,
      vpc: vpc,
      targetType: elb.TargetType.IP,
      targets: [ service ],
    });

    const listener = alb.addListener('Listener', {
      protocol: elb.ApplicationProtocol.HTTPS,
      port: 443,
      certificateArns: [ CERTIFICATE_ARN ],
      defaultTargetGroups: [tg]
    });

    const rule = new ApplicationListenerRule(this, 'rule', {
      listener,
      priority: 1,
      pathPattern: '*',
      targetGroups: [ tg ],
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

这是目标注册的结果。我需要这里的端口是443。 目标注册截图

小智 6

根据 的文档ecs.FargateService.loadBalancerTarget,将选择作为 ALB 目标的容器是任务定义中的第一个基本容器。

要使用其他容器,请创建如下服务引用:

const sTarget = service.loadBalancerTarget({
  containerName: 'MyContainer',
  containerPort: 1234
}));
Run Code Online (Sandbox Code Playgroud)

然后添加sTarget到targetGroup服务中。