Package software.amazon.awscdk.services.ecs.patterns


@Stability(Stable) @Deprecated package software.amazon.awscdk.services.ecs.patterns
Deprecated.

CDK Construct library for higher-level ECS Constructs

---

End-of-Support

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.

For more information on how to migrate, see the Migrating to AWS CDK v2 guide.


This library provides higher-level Amazon ECS constructs which follow common architectural patterns. It contains:

  • Application Load Balanced Services
  • Network Load Balanced Services
  • Queue Processing Services
  • Scheduled Tasks (cron jobs)
  • Additional Examples

Application Load Balanced Services

To define an Amazon ECS service that is behind an application load balancer, instantiate one of the following:

  • ApplicationLoadBalancedEc2Service

 Cluster cluster;
 
 ApplicationLoadBalancedEc2Service loadBalancedEcsService = ApplicationLoadBalancedEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("test"))
                 .environment(Map.of(
                         "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                         "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
                 .build())
         .desiredCount(2)
         .build();
 

  • ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 
 loadBalancedFargateService.targetGroup.configureHealthCheck(HealthCheck.builder()
         .path("/custom-health-path")
         .build());
 

Instead of providing a cluster you can specify a VPC and CDK will create a new ECS cluster. If you deploy multiple services CDK will only create one cluster per VPC.

You can omit cluster and vpc to let CDK create a new VPC with two AZs and create a cluster inside this VPC.

You can customize the health check for your target group; otherwise it defaults to HTTP over port 80 hitting path /.

Fargate services will use the LATEST platform version by default, but you can override by providing a value for the platformVersion property in the constructor.

Fargate services use the default VPC Security Group unless one or more are provided using the securityGroups property in the constructor.

By setting redirectHTTP to true, CDK will automatically create a listener on port 80 that redirects HTTP traffic to the HTTPS port.

If you specify the option recordType you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.

If you need to encrypt the traffic between the load balancer and the ECS tasks, you can set the targetProtocol to HTTPS.

Additionally, if more than one application target group are needed, instantiate one of the following:

  • ApplicationMultipleTargetGroupsEc2Service

 // One application load balancer with one listener and two target groups.
 Cluster cluster;
 
 ApplicationMultipleTargetGroupsEc2Service loadBalancedEc2Service = ApplicationMultipleTargetGroupsEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(256)
         .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .targetGroups(List.of(ApplicationTargetProps.builder()
                 .containerPort(80)
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(90)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .build()))
         .build();
 

  • ApplicationMultipleTargetGroupsFargateService

 // One application load balancer with one listener and two target groups.
 Cluster cluster;
 
 ApplicationMultipleTargetGroupsFargateService loadBalancedFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .targetGroups(List.of(ApplicationTargetProps.builder()
                 .containerPort(80)
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(90)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .build()))
         .build();
 

Network Load Balanced Services

To define an Amazon ECS service that is behind a network load balancer, instantiate one of the following:

  • NetworkLoadBalancedEc2Service

 Cluster cluster;
 
 NetworkLoadBalancedEc2Service loadBalancedEcsService = NetworkLoadBalancedEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("test"))
                 .environment(Map.of(
                         "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                         "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
                 .build())
         .desiredCount(2)
         .build();
 

  • NetworkLoadBalancedFargateService

 Cluster cluster;
 
 NetworkLoadBalancedFargateService loadBalancedFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 

The CDK will create a new Amazon ECS cluster if you specify a VPC and omit cluster. If you deploy multiple services the CDK will only create one cluster per VPC.

If cluster and vpc are omitted, the CDK creates a new VPC with subnets in two Availability Zones and a cluster within this VPC.

If you specify the option recordType you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.

Additionally, if more than one network target group is needed, instantiate one of the following:

  • NetworkMultipleTargetGroupsEc2Service

 // 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();
 

  • NetworkMultipleTargetGroupsFargateService

 // Two network load balancers, each with their own listener and target group.
 Cluster cluster;
 
 NetworkMultipleTargetGroupsFargateService loadBalancedFargateService = NetworkMultipleTargetGroupsFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .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();
 

Queue Processing Services

To define a service that creates a queue and reads from that queue, instantiate one of the following:

  • QueueProcessingEc2Service

 Cluster cluster;
 
 QueueProcessingEc2Service queueProcessingEc2Service = QueueProcessingEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of(
                 "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                 "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
         .maxScalingCapacity(5)
         .containerName("test")
         .build();
 

  • QueueProcessingFargateService

 Cluster cluster;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of(
                 "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                 "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
         .maxScalingCapacity(5)
         .containerName("test")
         .build();
 

when queue not provided by user, CDK will create a primary queue and a dead letter queue with default redrive policy and attach permission to the task to be able to access the primary queue.

Scheduled Tasks

To define a task that runs periodically, there are 2 options:

  • ScheduledEc2Task

 // Instantiate an Amazon EC2 Task to run at a scheduled interval
 Cluster cluster;
 
 ScheduledEc2Task ecsScheduledTask = ScheduledEc2Task.Builder.create(this, "ScheduledTask")
         .cluster(cluster)
         .scheduledEc2TaskImageOptions(ScheduledEc2TaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(256)
                 .environment(Map.of("name", "TRIGGER", "value", "CloudWatch Events"))
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .enabled(true)
         .ruleName("sample-scheduled-task-rule")
         .build();
 

  • ScheduledFargateTask

 Cluster cluster;
 
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .platformVersion(FargatePlatformVersion.LATEST)
         .build();
 

Additional Examples

In addition to using the constructs, users can also add logic to customize these constructs:

Configure HTTPS on an ApplicationLoadBalancedFargateService

 import software.amazon.awscdk.services.route53.HostedZone;
 import software.amazon.awscdk.services.certificatemanager.Certificate;
 import software.amazon.awscdk.services.elasticloadbalancingv2.SslPolicy;
 
 Vpc vpc;
 Cluster cluster;
 
 
 IHostedZone domainZone = HostedZone.fromLookup(this, "Zone", HostedZoneProviderProps.builder().domainName("example.com").build());
 ICertificate certificate = Certificate.fromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .cluster(cluster)
         .certificate(certificate)
         .sslPolicy(SslPolicy.RECOMMENDED)
         .domainName("api.example.com")
         .domainZone(domainZone)
         .redirectHTTP(true)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 

Add Schedule-Based Auto-Scaling to an ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 
 ScalableTaskCount scalableTarget = loadBalancedFargateService.service.autoScaleTaskCount(EnableScalingProps.builder()
         .minCapacity(5)
         .maxCapacity(20)
         .build());
 
 scalableTarget.scaleOnSchedule("DaytimeScaleDown", ScalingSchedule.builder()
         .schedule(Schedule.cron(CronOptions.builder().hour("8").minute("0").build()))
         .minCapacity(1)
         .build());
 
 scalableTarget.scaleOnSchedule("EveningRushScaleUp", ScalingSchedule.builder()
         .schedule(Schedule.cron(CronOptions.builder().hour("20").minute("0").build()))
         .minCapacity(10)
         .build());
 

Add Metric-Based Auto-Scaling to an ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 
 ScalableTaskCount scalableTarget = loadBalancedFargateService.service.autoScaleTaskCount(EnableScalingProps.builder()
         .minCapacity(1)
         .maxCapacity(20)
         .build());
 
 scalableTarget.scaleOnCpuUtilization("CpuScaling", CpuUtilizationScalingProps.builder()
         .targetUtilizationPercent(50)
         .build());
 
 scalableTarget.scaleOnMemoryUtilization("MemoryScaling", MemoryUtilizationScalingProps.builder()
         .targetUtilizationPercent(50)
         .build());
 

Change the default Deployment Controller

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .deploymentController(DeploymentController.builder()
                 .type(DeploymentControllerType.CODE_DEPLOY)
                 .build())
         .build();
 

Deployment circuit breaker and rollback

Amazon ECS deployment circuit breaker automatically rolls back unhealthy service deployments without the need for manual intervention. Use circuitBreaker to enable deployment circuit breaker and optionally enable rollback for automatic rollback. See Using the deployment circuit breaker for more details.

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService service = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .circuitBreaker(DeploymentCircuitBreaker.builder().rollback(true).build())
         .build();
 

Set deployment configuration on QueueProcessingService

 Cluster cluster;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of())
         .maxScalingCapacity(5)
         .maxHealthyPercent(200)
         .minHealthyPercent(66)
         .build();
 

Set taskSubnets and securityGroups for QueueProcessingFargateService

 Vpc vpc;
 SecurityGroup securityGroup;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .securityGroups(List.of(securityGroup))
         .taskSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_ISOLATED).build())
         .build();
 

Define tasks with public IPs for QueueProcessingFargateService

 Vpc vpc;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .assignPublicIp(true)
         .build();
 

Define tasks with custom queue parameters for QueueProcessingFargateService

 Vpc vpc;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .maxReceiveCount(42)
         .retentionPeriod(Duration.days(7))
         .visibilityTimeout(Duration.minutes(5))
         .build();
 

Set capacityProviderStrategies for QueueProcessingFargateService

 Cluster cluster;
 
 cluster.enableFargateCapacityProviders();
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                 .capacityProvider("FARGATE_SPOT")
                 .weight(2)
                 .build(), CapacityProviderStrategy.builder()
                 .capacityProvider("FARGATE")
                 .weight(1)
                 .build()))
         .build();
 

Set a custom container-level Healthcheck for QueueProcessingFargateService

 Vpc vpc;
 SecurityGroup securityGroup;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .healthCheck(HealthCheck.builder()
                 .command(List.of("CMD-SHELL", "curl -f http://localhost/ || exit 1"))
                 // the properties below are optional
                 .interval(Duration.minutes(30))
                 .retries(123)
                 .startPeriod(Duration.minutes(30))
                 .timeout(Duration.minutes(30))
                 .build())
         .build();
 

Set capacityProviderStrategies for QueueProcessingEc2Service

 import software.amazon.awscdk.services.autoscaling.*;
 
 
 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
 AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "asg")
         .vpc(vpc)
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
         .machineImage(EcsOptimizedImage.amazonLinux2())
         .build();
 AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "provider")
         .autoScalingGroup(autoScalingGroup)
         .build();
 cluster.addAsgCapacityProvider(capacityProvider);
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                 .capacityProvider(capacityProvider.getCapacityProviderName())
                 .build()))
         .build();
 

Select specific vpc subnets for ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .taskSubnets(SubnetSelection.builder()
                 .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                 .build())
         .build();
 

Set PlatformVersion for ScheduledFargateTask

 Cluster cluster;
 
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .platformVersion(FargatePlatformVersion.VERSION1_4)
         .build();
 

Set SecurityGroups for ScheduledFargateTask

 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
 SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SG").vpc(vpc).build();
 
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .securityGroups(List.of(securityGroup))
         .build();
 

Use the REMOVE_DEFAULT_DESIRED_COUNT feature flag

The REMOVE_DEFAULT_DESIRED_COUNT feature flag is used to override the default desiredCount that is autogenerated by the CDK. This will set the desiredCount of any service created by any of the following constructs to be undefined.

  • ApplicationLoadBalancedEc2Service
  • ApplicationLoadBalancedFargateService
  • NetworkLoadBalancedEc2Service
  • NetworkLoadBalancedFargateService
  • QueueProcessingEc2Service
  • QueueProcessingFargateService

If a desiredCount is not passed in as input to the above constructs, CloudFormation will either create a new service to start up with a desiredCount of 1, or update an existing service to start up with the same desiredCount as prior to the update.

To enable the feature flag, ensure that the REMOVE_DEFAULT_DESIRED_COUNT flag within an application stack context is set to true, like so:

 Stack stack;
 
 stack.node.setContext(ECS_REMOVE_DEFAULT_DESIRED_COUNT, true);
 

The following is an example of an application with the REMOVE_DEFAULT_DESIRED_COUNT feature flag enabled:

 import software.amazon.awscdk.core.App;
 import software.amazon.awscdk.core.Stack;
 import software.amazon.awscdk.services.ec2.*;
 import software.amazon.awscdk.services.ecs.*;
 import software.amazon.awscdk.services.ecs.patterns.*;
 import software.amazon.awscdk.cxapi.*;
 import path.*;
 
 App app = new App();
 
 Stack stack = new Stack(app, "aws-ecs-patterns-queue");
 stack.node.setContext(ECS_REMOVE_DEFAULT_DESIRED_COUNT, true);
 
 Vpc vpc = Vpc.Builder.create(stack, "VPC")
         .maxAzs(2)
         .build();
 
 QueueProcessingFargateService.Builder.create(stack, "QueueProcessingService")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(new AssetImage(join(__dirname, "..", "sqs-reader")))
         .build();
 

Deploy application and metrics sidecar

The following is an example of deploying an application along with a metrics sidecar container that utilizes dockerLabels for discovery:

 Cluster cluster;
 Vpc vpc;
 
 ApplicationLoadBalancedFargateService service = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .vpc(vpc)
         .desiredCount(1)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .dockerLabels(Map.of(
                         "application.label.one", "first_label",
                         "application.label.two", "second_label"))
                 .build())
         .build();
 
 service.taskDefinition.addContainer("Sidecar", ContainerDefinitionOptions.builder()
         .image(ContainerImage.fromRegistry("example/metrics-sidecar"))
         .build());
 

Select specific load balancer name ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .taskSubnets(SubnetSelection.builder()
                 .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                 .build())
         .loadBalancerName("application-lb-name")
         .build();
 
Deprecated: AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html