ApplicationLoadBalancedFargateService with load balancer, target groups, targets on non-standard port

0

I have an ECS service that exposes port 8080. I want to have the load balancer, target groups and target use that port as opposed to port 80. Here is a snippet of my code:

    const servicePort = 8888;
    const metricsPort = 8888;

    const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef');
    const repository = ecr.Repository.fromRepositoryName(this, 'cloud-config-server', 'cloud-config-server');

    taskDefinition.addContainer('Config', {
      image: ecs.ContainerImage.fromEcrRepository(repository),
      portMappings: [{containerPort : servicePort, hostPort: servicePort}],
    });
    
    const albFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'AlbConfigService', {
      cluster,
      publicLoadBalancer : false,
      taskDefinition: taskDefinition,
      desiredCount: 1,
    });

    const applicationTargetGroup = new elbv2.ApplicationTargetGroup(this, 'AlbConfigServiceTargetGroup', {
      targetType: elbv2.TargetType.IP,
      protocol: elbv2.ApplicationProtocol.HTTP,
      port: servicePort,
      vpc,
      healthCheck: {path: "/CloudConfigServer/actuator/env/profile", port: String(servicePort)}
    });

    const addApplicationTargetGroupsProps: elbv2.AddApplicationTargetGroupsProps = {
      targetGroups: [applicationTargetGroup],
    };

    albFargateService.loadBalancer.addListener('alb-listener', {
      protocol: elbv2.ApplicationProtocol.HTTP, port: servicePort, defaultTargetGroups: [applicationTargetGroup]}
    );
  }    
}

This does not work. The health check is taking place on port 80 with the default URL of "/" which fails, and the tasks are constantly recycled. A target group on port 8080, with the appropriate health check, is added, but it has no targets.

What is the recommended way to achieve load balancing on a port other than 80?

thanks

1 Answer
0
Accepted Answer

Hello there,

As ApplicationLoadBalancedFargateService is a high level construct, when using that we don't need to configure target group port and listener port (default will be 80 or 443). As long as we provide the container port (service port) in task definition, ApplicationLoadBalancedFargateService will take care of the port and connection configured correctly from ALB to ECS tasks.

So in your case, you don't need to specify applicationTargetGroup, addApplicationTargetGroupsProps, and albFargateService.loadBalancer.addListener. ApplicationLoadBalancedFargateService has already done that on your behalf.

You can reference to the doc to get a better understanding.

Let me know if you have any follow up questions.

SUPPORT ENGINEER
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions