Search code examples
typescriptamazon-web-servicesamazon-ecsaws-cdk

How to set the port of registered target by CDK


What I want to set is

ALB->(80)->TargetGroup->(80)->EC2(ECS node)
                      ->(8080)->EC2(for health check)

I use the ALB which is already existing.

So, my cdk script is like this below

At first make ECS Service

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

then make TargetGroup and add Service to TargetGroup.

 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
 });
 const targetGroup = new elb.ApplicationTargetGroup(this,"myapp-ECS", {
      targetGroupName:`myapp-${targetEnv}-tg`,
      port: 80,
      targets: [ecsAdminService],
      vpc: cluster.vpc,
 });
 existingListener.addTargetGroups("myapp-tg",{
      priority:5,
      conditions:[
        elb.ListenerCondition.hostHeaders(['myapp.example.jp'])
      ],
      targetGroups:[targetGroup]
 })
 targetGroup.configureHealthCheck({
      path: "/",
      port: "8080" 
 })

As a result, somehow port 8080 is used for registered targets.

enter image description here

However I want to use 80 here, and wonder why 8080 is used? (I only use the word 8080 in configureHealthCheck in cdk script)

and where can I set the register targets ports in cdk?


Solution

  • I use loadBalancerTarget, then it's solved.

    const targetGroup = new elb.ApplicationTargetGroup(this,"myapp-ECS", {
      targetGroupName:`myapp-${targetEnv}-tg`,
      port: 80,
      targets: [ecsAdminService.loadBalancerTarget({// add this
        containerName: `myapp-nginx-container`,
        containerPort: 80,
      })],
      vpc: cluster.vpc,
    });