Skip to content
v2.274.0

NetworkLoadBalancedEc2Service L3 construct ​

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

Example ​

ts
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';

declare const cluster: ecs.Cluster;
const certificate = Certificate.fromCertificateArn(this, 'Cert', 'arn:aws:acm:us-east-1:123456:certificate/abcdefg');
const loadBalancedEcsService = new ecsPatterns.NetworkLoadBalancedEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  // The default value of listenerPort is 443 if you pass in listenerCertificate
  // It is configured to port 4443 here
  listenerPort: 4443,
  listenerCertificate: certificate,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('test'),
    // The default value of containerPort is 443 if you pass in listenerCertificate
    // It is configured to port 8443 here
    containerPort: 8443,
    environment: {
      TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
      TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
    },
  },
  desiredCount: 2,
});
python
from aws_cdk.aws_certificatemanager import Certificate

# cluster: ecs.Cluster

certificate = Certificate.from_certificate_arn(self, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg")
load_balanced_ecs_service = ecs_patterns.NetworkLoadBalancedEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    # The default value of listenerPort is 443 if you pass in listenerCertificate
    # It is configured to port 4443 here
    listener_port=4443,
    listener_certificate=certificate,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("test"),
        # The default value of containerPort is 443 if you pass in listenerCertificate
        # It is configured to port 8443 here
        container_port=8443,
        environment={
            "TEST_ENVIRONMENT_VARIABLE1": "test environment variable 1 value",
            "TEST_ENVIRONMENT_VARIABLE2": "test environment variable 2 value"
        }
    ),
    desired_count=2
)
java
import software.amazon.awscdk.services.certificatemanager.Certificate;

Cluster cluster;

ICertificate certificate = Certificate.fromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
NetworkLoadBalancedEc2Service loadBalancedEcsService = NetworkLoadBalancedEc2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .memoryLimitMiB(1024)
        // The default value of listenerPort is 443 if you pass in listenerCertificate
        // It is configured to port 4443 here
        .listenerPort(4443)
        .listenerCertificate(certificate)
        .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("test"))
                // The default value of containerPort is 443 if you pass in listenerCertificate
                // It is configured to port 8443 here
                .containerPort(8443)
                .environment(Map.of(
                        "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                        "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
                .build())
        .desiredCount(2)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.CertificateManager;

Cluster cluster;

var certificate = Certificate.FromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
var loadBalancedEcsService = new NetworkLoadBalancedEc2Service(this, "Service", new NetworkLoadBalancedEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    // The default value of listenerPort is 443 if you pass in listenerCertificate
    // It is configured to port 4443 here
    ListenerPort = 4443,
    ListenerCertificate = certificate,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("test"),
        // The default value of containerPort is 443 if you pass in listenerCertificate
        // It is configured to port 8443 here
        ContainerPort = 8443,
        Environment = new Dictionary<string, string> {
            { "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
            { "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
        }
    },
    DesiredCount = 2
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"

var cluster Cluster

certificate := awscdk.Certificate_FromCertificateArn(this, jsii.String("Cert"), jsii.String("arn:aws:acm:us-east-1:123456:certificate/abcdefg"))
loadBalancedEcsService := ecsPatterns.NewNetworkLoadBalancedEc2Service(this, jsii.String("Service"), &NetworkLoadBalancedEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	// The default value of listenerPort is 443 if you pass in listenerCertificate
	// It is configured to port 4443 here
	ListenerPort: jsii.Number(4443),
	ListenerCertificate: certificate,
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
		// The default value of containerPort is 443 if you pass in listenerCertificate
		// It is configured to port 8443 here
		ContainerPort: jsii.Number(8443),
		Environment: map[string]*string{
			"TEST_ENVIRONMENT_VARIABLE1": jsii.String("test environment variable 1 value"),
			"TEST_ENVIRONMENT_VARIABLE2": jsii.String("test environment variable 2 value"),
		},
	},
	DesiredCount: jsii.Number(2),
})

Initializer ​

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

Construct Props ​

capacityProviderStrategiesoptionalCapacityProviderStrategy[]capacity_provider_strategiesoptionaltyping.List[CapacityProviderStrategy]capacityProviderStrategiesoptionalList<CapacityProviderStrategy>CapacityProviderStrategiesoptionalCapacityProviderStrategy[]CapacityProviderStrategiesoptional*[]CapacityProviderStrategy= undefined#
A list of Capacity Provider strategies used to place a service.
circuitBreakeroptionalDeploymentCircuitBreakercircuit_breakeroptionalDeploymentCircuitBreakercircuitBreakeroptionalDeploymentCircuitBreakerCircuitBreakeroptionalDeploymentCircuitBreakerCircuitBreakeroptionalDeploymentCircuitBreaker= disabled#
Whether to enable the deployment circuit breaker.

If this property is defined, circuit breaker will be implicitly enabled.

cloudMapOptionsoptionalCloudMapOptionscloud_map_optionsoptionalCloudMapOptionscloudMapOptionsoptionalCloudMapOptionsCloudMapOptionsoptionalCloudMapOptionsCloudMapOptionsoptionalCloudMapOptions#
The options for configuring an Amazon ECS service to use service discovery.

Default: AWS Cloud Map service discovery is not enabled.

clusteroptionalIClusterclusteroptionalIClusterclusteroptionalIClusterClusteroptionalIClusterClusteroptionalICluster#
The name of the cluster that hosts the service.

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

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

cpuoptionalnumbercpuoptionalint | floatcpuoptionalNumberCpuoptionaldoubleCpuoptional*float64= none#
The number of cpu units used by the task.
notes

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

256 (.25 vCPU) - Available memory values: 0.5GB, 1GB, 2GB

512 (.5 vCPU) - Available memory values: 1GB, 2GB, 3GB, 4GB

1024 (1 vCPU) - Available memory values: 2GB, 3GB, 4GB, 5GB, 6GB, 7GB, 8GB

2048 (2 vCPU) - Available memory values: Between 4GB and 16GB in 1GB increments

4096 (4 vCPU) - Available memory values: Between 8GB and 30GB in 1GB increments

This default is set in the underlying FargateTaskDefinition construct.

deploymentControlleroptionalDeploymentControllerdeployment_controlleroptionalDeploymentControllerdeploymentControlleroptionalDeploymentControllerDeploymentControlleroptionalDeploymentControllerDeploymentControlleroptionalDeploymentController#
Specifies which deployment controller to use for the service.

Default: Rolling update (ECS)

For more information, see Amazon ECS Deployment Types

desiredCountoptionalnumberdesired_countoptionalint | floatdesiredCountoptionalNumberDesiredCountoptionaldoubleDesiredCountoptional*float64#
The desired number of instantiations of the task definition to keep running on the service.

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

The minimum value is 1

domainNameoptionalstringdomain_nameoptionalstrdomainNameoptionalStringDomainNameoptionalstringDomainNameoptional*string#
The domain name for the service, e.g. "api.example.com.".

Default: No domain name.

domainZoneoptionalIHostedZonedomain_zoneoptionalIHostedZonedomainZoneoptionalIHostedZoneDomainZoneoptionalIHostedZoneDomainZoneoptionalIHostedZone#
The Route53 hosted zone for the domain, e.g. "example.com.".

Default: No Route53 hosted domain zone.

enableECSManagedTagsoptionalbooleanenable_ecs_managed_tagsoptionalboolenableECSManagedTagsoptionalBooleanEnableECSManagedTagsoptionalboolEnableECSManagedTagsoptional*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

enableExecuteCommandoptionalbooleanenable_execute_commandoptionalboolenableExecuteCommandoptionalBooleanEnableExecuteCommandoptionalboolEnableExecuteCommandoptional*bool= false#
Whether ECS Exec should be enabled.
healthCheckGracePeriodoptionalDurationhealth_check_grace_periodoptionalDurationhealthCheckGracePeriodoptionalDurationHealthCheckGracePeriodoptionalDurationHealthCheckGracePeriodoptionalDuration#
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: defaults to 60 seconds if at least one load balancer is in-use and it is not already set

ipAddressTypeoptionalIpAddressTypeip_address_typeoptionalIpAddressTypeipAddressTypeoptionalIpAddressTypeIpAddressTypeoptionalIpAddressTypeIpAddressTypeoptionalIpAddressType= IpAddressType.IPV4#
The type of IP addresses to use.

If you want to add a UDP or TCP_UDP listener to the load balancer, you must choose IPv4.

listenerCertificateoptionalIListenerCertificatelistener_certificateoptionalIListenerCertificatelistenerCertificateoptionalIListenerCertificateListenerCertificateoptionalIListenerCertificateListenerCertificateoptionalIListenerCertificate= none#
Listener certificate list of ACM cert ARNs.

If you provide a certificate, the listener's protocol will be TLS. If not, the listener's protocol will be TCP.

listenerPortoptionalnumberlistener_portoptionalint | floatlistenerPortoptionalNumberListenerPortoptionaldoubleListenerPortoptional*float64#
Listener port of the network load balancer that will serve traffic to the service.

Default: 80 or 443 with listenerCertificate provided

loadBalanceroptionalINetworkLoadBalancerload_balanceroptionalINetworkLoadBalancerloadBalanceroptionalINetworkLoadBalancerLoadBalanceroptionalINetworkLoadBalancerLoadBalanceroptionalINetworkLoadBalancer#
The network load balancer that will serve traffic to the service.

Default: a new load balancer will be created.

If the load balancer has been imported, the vpc attribute must be specified in the call to fromNetworkLoadBalancerAttributes().

[disable-awslint:ref-via-interface]

maxHealthyPercentoptionalnumbermax_healthy_percentoptionalint | floatmaxHealthyPercentoptionalNumberMaxHealthyPercentoptionaldoubleMaxHealthyPercentoptional*float64#
The maximum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that can run in a service during a deployment.

Default: 100 if daemon, otherwise 200

memoryLimitMiBoptionalnumbermemory_limit_mi_boptionalint | floatmemoryLimitMiBoptionalNumberMemoryLimitMiBoptionaldoubleMemoryLimitMiBoptional*float64#
The hard limit (in MiB) of memory to present to the container.

Default: No memory limit.

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

At least one of memoryLimitMiB and memoryReservationMiB is required.

memoryReservationMiBoptionalnumbermemory_reservation_mi_boptionalint | floatmemoryReservationMiBoptionalNumberMemoryReservationMiBoptionaldoubleMemoryReservationMiBoptional*float64#
The soft limit (in MiB) of memory to reserve for the container.

Default: No memory reserved.

notes

When system memory is under contention, Docker attempts to keep the container memory within the limit. If the container requires more memory, it can consume up to the value specified by the Memory property or all of the available memory on the container instance—whichever comes first.

At least one of memoryLimitMiB and memoryReservationMiB is required.

minHealthyPercentoptionalnumbermin_healthy_percentoptionalint | floatminHealthyPercentoptionalNumberMinHealthyPercentoptionaldoubleMinHealthyPercentoptional*float64#
The minimum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that must continue to run and remain healthy during a deployment.

Default: 0 if daemon, otherwise 50

placementConstraintsoptionalPlacementConstraint[]placement_constraintsoptionaltyping.List[PlacementConstraint]placementConstraintsoptionalList<PlacementConstraint>PlacementConstraintsoptionalPlacementConstraint[]PlacementConstraintsoptional*[]PlacementConstraint#
The placement constraints to use for tasks in the service.

Default: No constraints.

For more information, see Amazon ECS Task Placement Constraints.

placementStrategiesoptionalPlacementStrategy[]placement_strategiesoptionaltyping.List[PlacementStrategy]placementStrategiesoptionalList<PlacementStrategy>PlacementStrategiesoptionalPlacementStrategy[]PlacementStrategiesoptional*[]PlacementStrategy#
The placement strategies to use for tasks in the service.

Default: No strategies.

For more information, see Amazon ECS Task Placement Strategies.

propagateTagsoptionalPropagatedTagSourcepropagate_tagsoptionalPropagatedTagSourcepropagateTagsoptionalPropagatedTagSourcePropagateTagsoptionalPropagatedTagSourcePropagateTagsoptionalPropagatedTagSource= 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.

publicLoadBalanceroptionalbooleanpublic_load_balanceroptionalboolpublicLoadBalanceroptionalBooleanPublicLoadBalanceroptionalboolPublicLoadBalanceroptional*bool= true#
Determines whether the Load Balancer will be internet-facing.
Specifies whether the Route53 record should be a CNAME, an A record using the Alias feature or no record at all.

Default: NetworkLoadBalancedServiceRecordType.ALIAS

This is useful if you need to work with DNS systems that do not support alias records.

serviceNameoptionalstringservice_nameoptionalstrserviceNameoptionalStringServiceNameoptionalstringServiceNameoptional*string#
The name of the service.

Default: CloudFormation-generated name.

taskDefinitionoptionalEc2TaskDefinitiontask_definitionoptionalEc2TaskDefinitiontaskDefinitionoptionalEc2TaskDefinitionTaskDefinitionoptionalEc2TaskDefinitionTaskDefinitionoptionalEc2TaskDefinition= none#
The task definition to use for tasks in the service. TaskDefinition or TaskImageOptions must be specified, but not both..

[disable-awslint:ref-via-interface]

taskImageOptionsoptionalNetworkLoadBalancedTaskImageOptionstask_image_optionsoptionalNetworkLoadBalancedTaskImageOptionstaskImageOptionsoptionalNetworkLoadBalancedTaskImageOptionsTaskImageOptionsoptionalNetworkLoadBalancedTaskImageOptionsTaskImageOptionsoptionalNetworkLoadBalancedTaskImageOptions= none#
The properties required to create a new task definition.

One of taskImageOptions or taskDefinition must be specified.

vpcoptionalIVpcvpcoptionalIVpcvpcoptionalIVpcVpcoptionalIVpcVpcoptionalIVpc#
The VPC where the container instances will be launched or the elastic network interfaces (ENIs) will be deployed.

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

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

Properties ​

clusterIClusterclusterIClusterclusterIClusterClusterIClusterClusterIClusterrequired#
The cluster that hosts the service.
internalDesiredCountmay be undefinednumberinternal_desired_countmay be undefinedint | floatinternalDesiredCountmay be undefinedNumberInternalDesiredCountmay be undefineddoubleInternalDesiredCountmay be undefined*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.

The listener for the service.
loadBalancerNetworkLoadBalancerload_balancerNetworkLoadBalancerloadBalancerNetworkLoadBalancerLoadBalancerNetworkLoadBalancerLoadBalancerNetworkLoadBalancerrequired#
The Network Load Balancer for the service.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
serviceEc2ServiceserviceEc2ServiceserviceEc2ServiceServiceEc2ServiceServiceEc2Servicerequired#
The ECS service in this construct.
targetGroupNetworkTargetGrouptarget_groupNetworkTargetGrouptargetGroupNetworkTargetGroupTargetGroupNetworkTargetGroupTargetGroupNetworkTargetGrouprequired#
The target group for 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