Skip to content
v2.274.0

NetworkMultipleTargetGroupsEc2Service L3 construct ​

An EC2 service running on an ECS cluster fronted by a network load balancer.

Example ​

ts
// Two network load balancers, each with their own listener and target group.
declare const cluster: ecs.Cluster;
const loadBalancedEc2Service = new ecsPatterns.NetworkMultipleTargetGroupsEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 256,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  loadBalancers: [
    {
      name: 'lb1',
      listeners: [
        {
          name: 'listener1',
        },
      ],
    },
    {
      name: 'lb2',
      listeners: [
        {
          name: 'listener2',
        },
      ],
    },
  ],
  targetGroups: [
    {
      containerPort: 80,
      listener: 'listener1',
    },
    {
      containerPort: 90,
      listener: 'listener2',
    },
  ],
});
python
# Two network load balancers, each with their own listener and target group.
# cluster: ecs.Cluster

load_balanced_ec2_service = ecs_patterns.NetworkMultipleTargetGroupsEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=256,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageProps(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    load_balancers=[ecsPatterns.NetworkLoadBalancerProps(
        name="lb1",
        listeners=[ecsPatterns.NetworkListenerProps(
            name="listener1"
        )
        ]
    ), ecsPatterns.NetworkLoadBalancerProps(
        name="lb2",
        listeners=[ecsPatterns.NetworkListenerProps(
            name="listener2"
        )
        ]
    )
    ],
    target_groups=[ecsPatterns.NetworkTargetProps(
        container_port=80,
        listener="listener1"
    ), ecsPatterns.NetworkTargetProps(
        container_port=90,
        listener="listener2"
    )
    ]
)
java
// Two network load balancers, each with their own listener and target group.
Cluster cluster;

NetworkMultipleTargetGroupsEc2Service loadBalancedEc2Service = NetworkMultipleTargetGroupsEc2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .memoryLimitMiB(256)
        .taskImageOptions(NetworkLoadBalancedTaskImageProps.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .loadBalancers(List.of(NetworkLoadBalancerProps.builder()
                .name("lb1")
                .listeners(List.of(NetworkListenerProps.builder()
                        .name("listener1")
                        .build()))
                .build(), NetworkLoadBalancerProps.builder()
                .name("lb2")
                .listeners(List.of(NetworkListenerProps.builder()
                        .name("listener2")
                        .build()))
                .build()))
        .targetGroups(List.of(NetworkTargetProps.builder()
                .containerPort(80)
                .listener("listener1")
                .build(), NetworkTargetProps.builder()
                .containerPort(90)
                .listener("listener2")
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
// Two network load balancers, each with their own listener and target group.
Cluster cluster;

var loadBalancedEc2Service = new NetworkMultipleTargetGroupsEc2Service(this, "Service", new NetworkMultipleTargetGroupsEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 256,
    TaskImageOptions = new NetworkLoadBalancedTaskImageProps {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    LoadBalancers = new [] { new NetworkLoadBalancerProps {
        Name = "lb1",
        Listeners = new [] { new NetworkListenerProps {
            Name = "listener1"
        } }
    }, new NetworkLoadBalancerProps {
        Name = "lb2",
        Listeners = new [] { new NetworkListenerProps {
            Name = "listener2"
        } }
    } },
    TargetGroups = new [] { new NetworkTargetProps {
        ContainerPort = 80,
        Listener = "listener1"
    }, new NetworkTargetProps {
        ContainerPort = 90,
        Listener = "listener2"
    } }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Two network load balancers, each with their own listener and target group.
var cluster Cluster

loadBalancedEc2Service := ecsPatterns.NewNetworkMultipleTargetGroupsEc2Service(this, jsii.String("Service"), &NetworkMultipleTargetGroupsEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(256),
	TaskImageOptions: &NetworkLoadBalancedTaskImageProps{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	LoadBalancers: []NetworkLoadBalancerProps{
		&NetworkLoadBalancerProps{
			Name: jsii.String("lb1"),
			Listeners: []NetworkListenerProps{
				&NetworkListenerProps{
					Name: jsii.String("listener1"),
				},
			},
		},
		&NetworkLoadBalancerProps{
			Name: jsii.String("lb2"),
			Listeners: []NetworkListenerProps{
				&NetworkListenerProps{
					Name: jsii.String("listener2"),
				},
			},
		},
	},
	TargetGroups: []NetworkTargetProps{
		&NetworkTargetProps{
			ContainerPort: jsii.Number(80),
			Listener: jsii.String("listener1"),
		},
		&NetworkTargetProps{
			ContainerPort: jsii.Number(90),
			Listener: jsii.String("listener2"),
		},
	},
})

Initializer ​

ts
new NetworkMultipleTargetGroupsEc2Service(scope: Construct, id: string, props?: NetworkMultipleTargetGroupsEc2ServiceProps)
python
NetworkMultipleTargetGroupsEc2Service(scope: Construct, id: str, props: typing.Optional[NetworkMultipleTargetGroupsEc2ServiceProps] = None)
java
new NetworkMultipleTargetGroupsEc2Service(Construct scope, String id, NetworkMultipleTargetGroupsEc2ServiceProps props)
csharp
new NetworkMultipleTargetGroupsEc2Service(Construct scope, string id, NetworkMultipleTargetGroupsEc2ServiceProps? props = null)
go
NewNetworkMultipleTargetGroupsEc2Service(Scope Construct, Id *string, Props NetworkMultipleTargetGroupsEc2ServiceProps)

Construct Props ​

cloudMapOptionsCloudMapOptionscloud_map_optionsCloudMapOptionscloudMapOptionsCloudMapOptionsCloudMapOptionsCloudMapOptionsCloudMapOptionsCloudMapOptions= AWS Cloud Map service discovery …#
The options for configuring an Amazon ECS service to use service discovery.
default

Default: AWS Cloud Map service discovery is not enabled.

clusterIClusterclusterIClusterclusterIClusterClusterIClusterClusterICluster= create a new cluster; if both cl…#
The name of the cluster that hosts the service.

If a cluster is specified, the vpc construct should be omitted. Alternatively, you can omit both cluster and vpc.

default

Default: create a new cluster; if both cluster and vpc are omitted, a new VPC will be created for you.

cpunumbercpuint | floatcpuNumberCpudoubleCpu*float64= No minimum CPU units reserved.#
The minimum number of CPU units to reserve for the container.

Valid values, which determines your range of valid values for the memory parameter:

desiredCountnumberdesired_countint | floatdesiredCountNumberDesiredCountdoubleDesiredCount*float64= The default is 1 for all new ser…#
The desired number of instantiations of the task definition to keep running on the service.

The minimum value is 1

default

Default: The default is 1 for all new services and uses the existing service's desired count when updating an existing service.

enableECSManagedTagsbooleanenable_ecs_managed_tagsboolenableECSManagedTagsBooleanEnableECSManagedTagsboolEnableECSManagedTags*bool= false#
Specifies whether to enable Amazon ECS managed tags for the tasks within the service.

For more information, see Tagging Your Amazon ECS Resources

enableExecuteCommandbooleanenable_execute_commandboolenableExecuteCommandBooleanEnableExecuteCommandboolEnableExecuteCommand*bool= false#
Whether ECS Exec should be enabled.
healthCheckGracePeriodDurationhealth_check_grace_periodDurationhealthCheckGracePeriodDurationHealthCheckGracePeriodDurationHealthCheckGracePeriodDuration= defaults to 60 seconds if at lea…#
The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first started.
default

Default: defaults to 60 seconds if at least one load balancer is in-use and it is not already set

loadBalancersNetworkLoadBalancerProps[]load_balancerstyping.List[NetworkLoadBalancerProps]loadBalancersList<NetworkLoadBalancerProps>LoadBalancersNetworkLoadBalancerProps[]LoadBalancers*[]NetworkLoadBalancerProps= a new load balancer with a liste…#
The network load balancer that will serve traffic to the service.
default

Default: a new load balancer with a listener will be created.

memoryLimitMiBnumbermemory_limit_mi_bint | floatmemoryLimitMiBNumberMemoryLimitMiBdoubleMemoryLimitMiB*float64= No memory limit.#
The amount (in MiB) of memory to present to the container.

If your container attempts to exceed the allocated memory, the container is terminated.

At least one of memoryLimitMiB and memoryReservationMiB is required.

memoryReservationMiBnumbermemory_reservation_mi_bint | floatmemoryReservationMiBNumberMemoryReservationMiBdoubleMemoryReservationMiB*float64= No memory reserved.#
The soft limit (in MiB) of memory to reserve for the container.
notes

When system memory is under heavy contention, Docker attempts to keep the container memory to this soft limit. However, your container can consume more memory when it needs to, up to either the hard limit specified with the memory parameter (if applicable), or all of the available memory on the container instance, whichever comes first.

At least one of memoryLimitMiB and memoryReservationMiB is required.

Note that this setting will be ignored if TaskImagesOptions is specified.

placementConstraintsPlacementConstraint[]placement_constraintstyping.List[PlacementConstraint]placementConstraintsList<PlacementConstraint>PlacementConstraintsPlacementConstraint[]PlacementConstraints*[]PlacementConstraint= No constraints.#
The placement constraints to use for tasks in the service.

For more information, see Amazon ECS Task Placement Constraints.

placementStrategiesPlacementStrategy[]placement_strategiestyping.List[PlacementStrategy]placementStrategiesList<PlacementStrategy>PlacementStrategiesPlacementStrategy[]PlacementStrategies*[]PlacementStrategy= No strategies.#
The placement strategies to use for tasks in the service.

For more information, see Amazon ECS Task Placement Strategies.

propagateTagsPropagatedTagSourcepropagate_tagsPropagatedTagSourcepropagateTagsPropagatedTagSourcePropagateTagsPropagatedTagSourcePropagateTagsPropagatedTagSource= none#
Specifies whether to propagate the tags from the task definition or the service to the tasks in the service.

Tags can only be propagated to the tasks within the service during service creation.

serviceNamestringservice_namestrserviceNameStringServiceNamestringServiceName*string= CloudFormation-generated name.#
Name of the service.
targetGroupsNetworkTargetProps[]target_groupstyping.List[NetworkTargetProps]targetGroupsList<NetworkTargetProps>TargetGroupsNetworkTargetProps[]TargetGroups*[]NetworkTargetProps= default portMapping registered a…#
Properties to specify NLB target groups.
default

Default: default portMapping registered as target group and attached to the first defined listener

taskDefinitionEc2TaskDefinitiontask_definitionEc2TaskDefinitiontaskDefinitionEc2TaskDefinitionTaskDefinitionEc2TaskDefinitionTaskDefinitionEc2TaskDefinition= none#
The task definition to use for tasks in the service. Only one of TaskDefinition or TaskImageOptions must be specified.

[disable-awslint:ref-via-interface]

The properties required to create a new task definition.

Only one of TaskDefinition or TaskImageOptions must be specified.

vpcIVpcvpcIVpcvpcIVpcVpcIVpcVpcIVpc= uses the VPC defined in the clus…#
The VPC where the container instances will be launched or the elastic network interfaces (ENIs) will be deployed.

If a vpc is specified, the cluster construct should be omitted. Alternatively, you can omit both vpc and cluster.

default

Default: uses the VPC defined in the cluster or creates a new VPC.

Properties ​

clusterIClusterclusterIClusterclusterIClusterClusterIClusterClusterIClusterrequired#
The cluster that hosts the service.
internalDesiredCountnumberinternal_desired_countint | floatinternalDesiredCountNumberInternalDesiredCountdoubleInternalDesiredCount*float64#
The desired number of instantiations of the task definition to keep running on the service.

The default is 1 for all new services and uses the existing services desired count when updating an existing service, if one is not provided.

listenerNetworkListenerlistenerNetworkListenerlistenerNetworkListenerListenerNetworkListenerListenerNetworkListenerrequireddeprecated#
- Use `listeners` instead.
listenersNetworkListener[]listenerstyping.List[NetworkListener]listenersList<NetworkListener>ListenersNetworkListener[]Listeners*[]NetworkListenerrequired#
The listeners of the service.
loadBalancerNetworkLoadBalancerload_balancerNetworkLoadBalancerloadBalancerNetworkLoadBalancerLoadBalancerNetworkLoadBalancerLoadBalancerNetworkLoadBalancerrequireddeprecated#
- Use `loadBalancers` instead.
loadBalancersNetworkLoadBalancer[]load_balancerstyping.List[NetworkLoadBalancer]loadBalancersList<NetworkLoadBalancer>LoadBalancersNetworkLoadBalancer[]LoadBalancers*[]NetworkLoadBalancerrequired#
The load balancers of the service.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
serviceEc2ServiceserviceEc2ServiceserviceEc2ServiceServiceEc2ServiceServiceEc2Servicerequired#
The EC2 service in this construct.
targetGroupNetworkTargetGrouptarget_groupNetworkTargetGrouptargetGroupNetworkTargetGroupTargetGroupNetworkTargetGroupTargetGroupNetworkTargetGrouprequireddeprecated#
- Use `targetGroups` instead.
targetGroupsNetworkTargetGroup[]target_groupstyping.List[NetworkTargetGroup]targetGroupsList<NetworkTargetGroup>TargetGroupsNetworkTargetGroup[]TargetGroups*[]NetworkTargetGrouprequired#
The target groups of the service.
taskDefinitionEc2TaskDefinitiontask_definitionEc2TaskDefinitiontaskDefinitionEc2TaskDefinitionTaskDefinitionEc2TaskDefinitionTaskDefinitionEc2TaskDefinitionrequired#
The EC2 Task Definition in this construct.

Methods ​

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining