Skip to content

(ecs-patterns): NetworkLoadBalancedServiceBase does not support container port mapping using taskDefinition #29041

@jackdreinhardt

Description

@jackdreinhardt

Describe the bug

When initializing the NetworkBalancedServiceBase with a taskDefinition, there is no way to set the target group port to a value other than 80.

Expected Behavior

I expect the target group port of the load balancer to be set to the taskDefinition's default container container port.

Current Behavior

The target group port is 80, different from the task definition's default container port mapping configuration.

Reproduction Steps

import { Stack, StackProps } from 'aws-cdk-lib';
import { Vpc } from 'aws-cdk-lib/aws-ec2';
import { Cluster, ContainerImage } from 'aws-cdk-lib/aws-ecs';
import { NetworkLoadBalancedFargateService } from 'aws-cdk-lib/aws-ecs-patterns';
import { Construct } from 'constructs';

export class ElbTestStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const vpc = new Vpc(this, 'vpc', {});

    const fargateCluster = new Cluster(this, 'Cluster', {
      clusterName: 'test',
      vpc: vpc,
      enableFargateCapacityProviders: true,
      containerInsights: true
    })

    this.taskDefinition = new FargateTaskDefinition(this, 'TaskDefinition', {
            cpu: 0.5,
            memoryLimitMiB: 1,
    });
    this.taskDefinition.addContainer('service', {
        image: ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
        portMappings: [{containerPort: 81}]
    })

    const loadBalancedFargateService = new NetworkLoadBalancedFargateService(this, 'NLBService', {
      cluster: fargateCluster,
      memoryLimitMiB: 1024,
      cpu: 512,
      taskDefinition: this.taskDefinition,
      listenerPort: 8181,
    });
  }
}

Possible Solution

Currently, the logic to set the target port is as follows

const targetProps = {
  port: props.taskImageOptions?.containerPort ?? 80,
};

https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/aws-ecs-patterns/lib/base/network-load-balanced-service-base.ts#L361

It needs to be changed to something like this:

const targetProps = {
  port: props.taskImageOptions?.containerPort ?? props.taskDefinition.defaultContainer.portMappings[0].containerPort ?? 80
}

Additional Information/Context

No response

CDK CLI Version

2.100.0

Framework Version

No response

Node.js Version

18

OS

AL2

Language

TypeScript

Language Version

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    @aws-cdk/aws-ecs-patternsRelated to ecs-patterns libraryeffort/mediumMedium work item – several days of effortfeature-requestA feature should be added or improved.p2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions