Skip to content
v2.274.0

CDK Construct library for higher-level ECS Constructs ​

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
ts
declare const cluster: ecs.Cluster;
const loadBalancedEcsService = new ecsPatterns.ApplicationLoadBalancedEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('test'),
    environment: {
      TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
      TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
    },
    command: ['command'],
    entryPoint: ['entry', 'point'],
  },
  desiredCount: 2,
  minHealthyPercent: 100,
});
python
# cluster: ecs.Cluster

load_balanced_ecs_service = ecs_patterns.ApplicationLoadBalancedEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("test"),
        environment={
            "TEST_ENVIRONMENT_VARIABLE1": "test environment variable 1 value",
            "TEST_ENVIRONMENT_VARIABLE2": "test environment variable 2 value"
        },
        command=["command"],
        entry_point=["entry", "point"]
    ),
    desired_count=2,
    min_healthy_percent=100
)
java
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"))
                .command(List.of("command"))
                .entryPoint(List.of("entry", "point"))
                .build())
        .desiredCount(2)
        .minHealthyPercent(100)
        .build();
csharp
Cluster cluster;

var loadBalancedEcsService = new ApplicationLoadBalancedEc2Service(this, "Service", new ApplicationLoadBalancedEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("test"),
        Environment = new Dictionary<string, string> {
            { "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
            { "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
        },
        Command = new [] { "command" },
        EntryPoint = new [] { "entry", "point" }
    },
    DesiredCount = 2,
    MinHealthyPercent = 100
});
go
var cluster Cluster

loadBalancedEcsService := ecsPatterns.NewApplicationLoadBalancedEc2Service(this, jsii.String("Service"), &ApplicationLoadBalancedEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
		Environment: map[string]*string{
			"TEST_ENVIRONMENT_VARIABLE1": jsii.String("test environment variable 1 value"),
			"TEST_ENVIRONMENT_VARIABLE2": jsii.String("test environment variable 2 value"),
		},
		Command: []*string{
			jsii.String("command"),
		},
		EntryPoint: []*string{
			jsii.String("entry"),
			jsii.String("point"),
		},
	},
	DesiredCount: jsii.Number(2),
	MinHealthyPercent: jsii.Number(100),
})
  • ApplicationLoadBalancedFargateService
ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
    command: ['command'],
    entryPoint: ['entry', 'point'],
  },
  containerCpu: 256,
  containerMemoryLimitMiB: 512,
  minHealthyPercent: 100,
});

loadBalancedFargateService.targetGroup.configureHealthCheck({
  path: "/custom-health-path",
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        command=["command"],
        entry_point=["entry", "point"]
    ),
    container_cpu=256,
    container_memory_limit_mi_b=512,
    min_healthy_percent=100
)

load_balanced_fargate_service.target_group.configure_health_check(
    path="/custom-health-path"
)
java
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"))
                .command(List.of("command"))
                .entryPoint(List.of("entry", "point"))
                .build())
        .containerCpu(256)
        .containerMemoryLimitMiB(512)
        .minHealthyPercent(100)
        .build();

loadBalancedFargateService.targetGroup.configureHealthCheck(HealthCheck.builder()
        .path("/custom-health-path")
        .build());
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        Command = new [] { "command" },
        EntryPoint = new [] { "entry", "point" }
    },
    ContainerCpu = 256,
    ContainerMemoryLimitMiB = 512,
    MinHealthyPercent = 100
});

loadBalancedFargateService.TargetGroup.ConfigureHealthCheck(new HealthCheck {
    Path = "/custom-health-path"
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		Command: []*string{
			jsii.String("command"),
		},
		EntryPoint: []*string{
			jsii.String("entry"),
			jsii.String("point"),
		},
	},
	ContainerCpu: jsii.Number(256),
	ContainerMemoryLimitMiB: jsii.Number(512),
	MinHealthyPercent: jsii.Number(100),
})

loadBalancedFargateService.TargetGroup.ConfigureHealthCheck(&HealthCheck{
	Path: jsii.String("/custom-health-path"),
})

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 /.

You can customize the health check configuration of the container via the healthCheck property; otherwise it defaults to the health check configuration from the container.

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.

Security Considerations: When using custom security groups on your load balancer, the openListener property controls whether the load balancer listener allows traffic from anywhere on the internet (0.0.0.0/0). By default, openListener is true, but it will automatically default to false when custom security groups are detected, preventing unintended internet exposure. You can always explicitly set openListener: true to override this behavior if needed.

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.

To set the minimum number of CPU units to reserve for the container, you can use the containerCpu property.

To set the amount of memory (in MiB) to provide to the container, you can use the containerMemoryLimitMiB property.

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
ts
// One application load balancer with one listener and two target groups.
declare const cluster: ecs.Cluster;
const loadBalancedEc2Service = new ecsPatterns.ApplicationMultipleTargetGroupsEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 256,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  targetGroups: [
    {
      containerPort: 80,
    },
    {
      containerPort: 90,
      pathPattern: 'a/b/c',
      priority: 10,
    },
  ],
});
python
# One application load balancer with one listener and two target groups.
# cluster: ecs.Cluster

load_balanced_ec2_service = ecs_patterns.ApplicationMultipleTargetGroupsEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=256,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageProps(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    target_groups=[ecsPatterns.ApplicationTargetProps(
        container_port=80
    ), ecsPatterns.ApplicationTargetProps(
        container_port=90,
        path_pattern="a/b/c",
        priority=10
    )
    ]
)
java
// 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();
csharp
// One application load balancer with one listener and two target groups.
Cluster cluster;

var loadBalancedEc2Service = new ApplicationMultipleTargetGroupsEc2Service(this, "Service", new ApplicationMultipleTargetGroupsEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 256,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    TargetGroups = new [] { new ApplicationTargetProps {
        ContainerPort = 80
    }, new ApplicationTargetProps {
        ContainerPort = 90,
        PathPattern = "a/b/c",
        Priority = 10
    } }
});
go
// One application load balancer with one listener and two target groups.
var cluster Cluster

loadBalancedEc2Service := ecsPatterns.NewApplicationMultipleTargetGroupsEc2Service(this, jsii.String("Service"), &ApplicationMultipleTargetGroupsEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(256),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageProps{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	TargetGroups: []ApplicationTargetProps{
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(80),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(90),
			PathPattern: jsii.String("a/b/c"),
			Priority: jsii.Number(10),
		},
	},
})
  • ApplicationMultipleTargetGroupsFargateService
ts
// One application load balancer with one listener and two target groups.
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationMultipleTargetGroupsFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  targetGroups: [
    {
      containerPort: 80,
    },
    {
      containerPort: 90,
      pathPattern: 'a/b/c',
      priority: 10,
    },
  ],
});
python
# One application load balancer with one listener and two target groups.
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationMultipleTargetGroupsFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageProps(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    target_groups=[ecsPatterns.ApplicationTargetProps(
        container_port=80
    ), ecsPatterns.ApplicationTargetProps(
        container_port=90,
        path_pattern="a/b/c",
        priority=10
    )
    ]
)
java
// 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();
csharp
// One application load balancer with one listener and two target groups.
Cluster cluster;

var loadBalancedFargateService = new ApplicationMultipleTargetGroupsFargateService(this, "Service", new ApplicationMultipleTargetGroupsFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    TargetGroups = new [] { new ApplicationTargetProps {
        ContainerPort = 80
    }, new ApplicationTargetProps {
        ContainerPort = 90,
        PathPattern = "a/b/c",
        Priority = 10
    } }
});
go
// One application load balancer with one listener and two target groups.
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationMultipleTargetGroupsFargateService(this, jsii.String("Service"), &ApplicationMultipleTargetGroupsFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageProps{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	TargetGroups: []ApplicationTargetProps{
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(80),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(90),
			PathPattern: jsii.String("a/b/c"),
			Priority: jsii.Number(10),
		},
	},
})

Network Load Balanced Services ​

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

  • NetworkLoadBalancedEc2Service
ts
declare const cluster: ecs.Cluster;
const loadBalancedEcsService = new ecsPatterns.NetworkLoadBalancedEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('test'),
    environment: {
      TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
      TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
    },
  },
  desiredCount: 2,
  minHealthyPercent: 100,
});
python
# cluster: ecs.Cluster

load_balanced_ecs_service = ecs_patterns.NetworkLoadBalancedEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("test"),
        environment={
            "TEST_ENVIRONMENT_VARIABLE1": "test environment variable 1 value",
            "TEST_ENVIRONMENT_VARIABLE2": "test environment variable 2 value"
        }
    ),
    desired_count=2,
    min_healthy_percent=100
)
java
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)
        .minHealthyPercent(100)
        .build();
csharp
Cluster cluster;

var loadBalancedEcsService = new NetworkLoadBalancedEc2Service(this, "Service", new NetworkLoadBalancedEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("test"),
        Environment = new Dictionary<string, string> {
            { "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
            { "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
        }
    },
    DesiredCount = 2,
    MinHealthyPercent = 100
});
go
var cluster Cluster

loadBalancedEcsService := ecsPatterns.NewNetworkLoadBalancedEc2Service(this, jsii.String("Service"), &NetworkLoadBalancedEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
		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),
	MinHealthyPercent: jsii.Number(100),
})
  • NetworkLoadBalancedFargateService
ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.NetworkLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.NetworkLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    cpu=512,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100
)
java
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())
        .minHealthyPercent(100)
        .build();
csharp
Cluster cluster;

var loadBalancedFargateService = new NetworkLoadBalancedFargateService(this, "Service", new NetworkLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    Cpu = 512,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewNetworkLoadBalancedFargateService(this, jsii.String("Service"), &NetworkLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	Cpu: jsii.Number(512),
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
})

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
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
// 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
// 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"),
		},
	},
})
  • NetworkMultipleTargetGroupsFargateService
ts
// Two network load balancers, each with their own listener and target group.
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.NetworkMultipleTargetGroupsFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  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',
    },
  ],
  minHealthyPercent: 100,
  maxHealthyPercent: 200,
});
python
# Two network load balancers, each with their own listener and target group.
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.NetworkMultipleTargetGroupsFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    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"
    )
    ],
    min_healthy_percent=100,
    max_healthy_percent=200
)
java
// 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()))
        .minHealthyPercent(100)
        .maxHealthyPercent(200)
        .build();
csharp
// Two network load balancers, each with their own listener and target group.
Cluster cluster;

var loadBalancedFargateService = new NetworkMultipleTargetGroupsFargateService(this, "Service", new NetworkMultipleTargetGroupsFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    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"
    } },
    MinHealthyPercent = 100,
    MaxHealthyPercent = 200
});
go
// Two network load balancers, each with their own listener and target group.
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewNetworkMultipleTargetGroupsFargateService(this, jsii.String("Service"), &NetworkMultipleTargetGroupsFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	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"),
		},
	},
	MinHealthyPercent: jsii.Number(100),
	MaxHealthyPercent: jsii.Number(200),
})

Queue Processing Services ​

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

  • QueueProcessingEc2Service
ts
declare const cluster: ecs.Cluster;
const queueProcessingEc2Service = new ecsPatterns.QueueProcessingEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  image: ecs.ContainerImage.fromRegistry('test'),
  command: ["-c", "4", "amazon.com"],
  enableLogging: false,
  desiredTaskCount: 2,
  environment: {
    TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
    TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
  },
  maxScalingCapacity: 5,
  containerName: 'test',
  minHealthyPercent: 100,
});
python
# cluster: ecs.Cluster

queue_processing_ec2_service = ecs_patterns.QueueProcessingEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    image=ecs.ContainerImage.from_registry("test"),
    command=["-c", "4", "amazon.com"],
    enable_logging=False,
    desired_task_count=2,
    environment={
        "TEST_ENVIRONMENT_VARIABLE1": "test environment variable 1 value",
        "TEST_ENVIRONMENT_VARIABLE2": "test environment variable 2 value"
    },
    max_scaling_capacity=5,
    container_name="test",
    min_healthy_percent=100
)
java
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")
        .minHealthyPercent(100)
        .build();
csharp
Cluster cluster;

var queueProcessingEc2Service = new QueueProcessingEc2Service(this, "Service", new QueueProcessingEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    Image = ContainerImage.FromRegistry("test"),
    Command = new [] { "-c", "4", "amazon.com" },
    EnableLogging = false,
    DesiredTaskCount = 2,
    Environment = new Dictionary<string, string> {
        { "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
        { "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
    },
    MaxScalingCapacity = 5,
    ContainerName = "test",
    MinHealthyPercent = 100
});
go
var cluster Cluster

queueProcessingEc2Service := ecsPatterns.NewQueueProcessingEc2Service(this, jsii.String("Service"), &QueueProcessingEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	Command: []*string{
		jsii.String("-c"),
		jsii.String("4"),
		jsii.String("amazon.com"),
	},
	EnableLogging: jsii.Boolean(false),
	DesiredTaskCount: jsii.Number(2),
	Environment: map[string]*string{
		"TEST_ENVIRONMENT_VARIABLE1": jsii.String("test environment variable 1 value"),
		"TEST_ENVIRONMENT_VARIABLE2": jsii.String("test environment variable 2 value"),
	},
	MaxScalingCapacity: jsii.Number(5),
	ContainerName: jsii.String("test"),
	MinHealthyPercent: jsii.Number(100),
})
  • QueueProcessingFargateService
ts
declare const cluster: ecs.Cluster;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  command: ["-c", "4", "amazon.com"],
  enableLogging: false,
  desiredTaskCount: 2,
  environment: {
    TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
    TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
  },
  maxScalingCapacity: 5,
  containerName: 'test',
  minHealthyPercent: 100,
});
python
# cluster: ecs.Cluster

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    command=["-c", "4", "amazon.com"],
    enable_logging=False,
    desired_task_count=2,
    environment={
        "TEST_ENVIRONMENT_VARIABLE1": "test environment variable 1 value",
        "TEST_ENVIRONMENT_VARIABLE2": "test environment variable 2 value"
    },
    max_scaling_capacity=5,
    container_name="test",
    min_healthy_percent=100
)
java
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")
        .minHealthyPercent(100)
        .build();
csharp
Cluster cluster;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    Command = new [] { "-c", "4", "amazon.com" },
    EnableLogging = false,
    DesiredTaskCount = 2,
    Environment = new Dictionary<string, string> {
        { "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
        { "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
    },
    MaxScalingCapacity = 5,
    ContainerName = "test",
    MinHealthyPercent = 100
});
go
var cluster Cluster

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	Command: []*string{
		jsii.String("-c"),
		jsii.String("4"),
		jsii.String("amazon.com"),
	},
	EnableLogging: jsii.Boolean(false),
	DesiredTaskCount: jsii.Number(2),
	Environment: map[string]*string{
		"TEST_ENVIRONMENT_VARIABLE1": jsii.String("test environment variable 1 value"),
		"TEST_ENVIRONMENT_VARIABLE2": jsii.String("test environment variable 2 value"),
	},
	MaxScalingCapacity: jsii.Number(5),
	ContainerName: jsii.String("test"),
	MinHealthyPercent: jsii.Number(100),
})

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.

NOTE: QueueProcessingFargateService adds a CPU Based scaling strategy by default. You can turn this off by setting disableCpuBasedScaling: true.

ts
declare const cluster: ecs.Cluster;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  command: ["-c", "4", "amazon.com"],
  enableLogging: false,
  desiredTaskCount: 2,
  environment: {
    TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
    TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
  },
  maxScalingCapacity: 5,
  containerName: 'test',
  minHealthyPercent: 100,
  disableCpuBasedScaling: true,
});
python
# cluster: ecs.Cluster

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    command=["-c", "4", "amazon.com"],
    enable_logging=False,
    desired_task_count=2,
    environment={
        "TEST_ENVIRONMENT_VARIABLE1": "test environment variable 1 value",
        "TEST_ENVIRONMENT_VARIABLE2": "test environment variable 2 value"
    },
    max_scaling_capacity=5,
    container_name="test",
    min_healthy_percent=100,
    disable_cpu_based_scaling=True
)
java
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")
        .minHealthyPercent(100)
        .disableCpuBasedScaling(true)
        .build();
csharp
Cluster cluster;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    Command = new [] { "-c", "4", "amazon.com" },
    EnableLogging = false,
    DesiredTaskCount = 2,
    Environment = new Dictionary<string, string> {
        { "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
        { "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
    },
    MaxScalingCapacity = 5,
    ContainerName = "test",
    MinHealthyPercent = 100,
    DisableCpuBasedScaling = true
});
go
var cluster Cluster

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	Command: []*string{
		jsii.String("-c"),
		jsii.String("4"),
		jsii.String("amazon.com"),
	},
	EnableLogging: jsii.Boolean(false),
	DesiredTaskCount: jsii.Number(2),
	Environment: map[string]*string{
		"TEST_ENVIRONMENT_VARIABLE1": jsii.String("test environment variable 1 value"),
		"TEST_ENVIRONMENT_VARIABLE2": jsii.String("test environment variable 2 value"),
	},
	MaxScalingCapacity: jsii.Number(5),
	ContainerName: jsii.String("test"),
	MinHealthyPercent: jsii.Number(100),
	DisableCpuBasedScaling: jsii.Boolean(true),
})

To specify a custom target CPU utilization percentage for the scaling strategy use the cpuTargetUtilizationPercent property:

ts
declare const cluster: ecs.Cluster;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  command: ["-c", "4", "amazon.com"],
  enableLogging: false,
  desiredTaskCount: 2,
  environment: {},
  maxScalingCapacity: 5,
  containerName: 'test',
  minHealthyPercent: 100,
  cpuTargetUtilizationPercent: 90,
});
python
# cluster: ecs.Cluster

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    command=["-c", "4", "amazon.com"],
    enable_logging=False,
    desired_task_count=2,
    environment={},
    max_scaling_capacity=5,
    container_name="test",
    min_healthy_percent=100,
    cpu_target_utilization_percent=90
)
java
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)
        .containerName("test")
        .minHealthyPercent(100)
        .cpuTargetUtilizationPercent(90)
        .build();
csharp
Cluster cluster;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    Command = new [] { "-c", "4", "amazon.com" },
    EnableLogging = false,
    DesiredTaskCount = 2,
    Environment = new Dictionary<string, object> { },
    MaxScalingCapacity = 5,
    ContainerName = "test",
    MinHealthyPercent = 100,
    CpuTargetUtilizationPercent = 90
});
go
var cluster Cluster

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	Command: []*string{
		jsii.String("-c"),
		jsii.String("4"),
		jsii.String("amazon.com"),
	},
	EnableLogging: jsii.Boolean(false),
	DesiredTaskCount: jsii.Number(2),
	Environment: map[string]interface{}{
	},
	MaxScalingCapacity: jsii.Number(5),
	ContainerName: jsii.String("test"),
	MinHealthyPercent: jsii.Number(100),
	CpuTargetUtilizationPercent: jsii.Number(90),
})

Scheduled Tasks ​

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

  • ScheduledEc2Task
ts
// Instantiate an Amazon EC2 Task to run at a scheduled interval
declare const cluster: ecs.Cluster;
const ecsScheduledTask = new ecsPatterns.ScheduledEc2Task(this, 'ScheduledTask', {
  cluster,
  scheduledEc2TaskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
    memoryLimitMiB: 256,
    environment: { name: 'TRIGGER', value: 'CloudWatch Events' },
  },
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  enabled: true,
  ruleName: 'sample-scheduled-task-rule',
});
python
# Instantiate an Amazon EC2 Task to run at a scheduled interval
# cluster: ecs.Cluster

ecs_scheduled_task = ecs_patterns.ScheduledEc2Task(self, "ScheduledTask",
    cluster=cluster,
    scheduled_ec2_task_image_options=ecsPatterns.ScheduledEc2TaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        memory_limit_mi_b=256,
        environment={"name": "TRIGGER", "value": "CloudWatch Events"}
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    enabled=True,
    rule_name="sample-scheduled-task-rule"
)
java
// 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();
csharp
// Instantiate an Amazon EC2 Task to run at a scheduled interval
Cluster cluster;

var ecsScheduledTask = new ScheduledEc2Task(this, "ScheduledTask", new ScheduledEc2TaskProps {
    Cluster = cluster,
    ScheduledEc2TaskImageOptions = new ScheduledEc2TaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        MemoryLimitMiB = 256,
        Environment = new Dictionary<string, string> { { "name", "TRIGGER" }, { "value", "CloudWatch Events" } }
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    Enabled = true,
    RuleName = "sample-scheduled-task-rule"
});
go
// Instantiate an Amazon EC2 Task to run at a scheduled interval
var cluster Cluster

ecsScheduledTask := ecsPatterns.NewScheduledEc2Task(this, jsii.String("ScheduledTask"), &ScheduledEc2TaskProps{
	Cluster: Cluster,
	ScheduledEc2TaskImageOptions: &ScheduledEc2TaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		MemoryLimitMiB: jsii.Number(256),
		Environment: map[string]*string{
			"name": jsii.String("TRIGGER"),
			"value": jsii.String("CloudWatch Events"),
		},
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	Enabled: jsii.Boolean(true),
	RuleName: jsii.String("sample-scheduled-task-rule"),
})
  • ScheduledFargateTask
ts
declare const cluster: ecs.Cluster;
const scheduledFargateTask = new ecsPatterns.ScheduledFargateTask(this, 'ScheduledFargateTask', {
  cluster,
  scheduledFargateTaskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
    memoryLimitMiB: 512,
  },
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  platformVersion: ecs.FargatePlatformVersion.LATEST,
});
python
# cluster: ecs.Cluster

scheduled_fargate_task = ecs_patterns.ScheduledFargateTask(self, "ScheduledFargateTask",
    cluster=cluster,
    scheduled_fargate_task_image_options=ecsPatterns.ScheduledFargateTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        memory_limit_mi_b=512
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    platform_version=ecs.FargatePlatformVersion.LATEST
)
java
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();
csharp
Cluster cluster;

var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
    Cluster = cluster,
    ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        MemoryLimitMiB = 512
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    PlatformVersion = FargatePlatformVersion.LATEST
});
go
var cluster Cluster

scheduledFargateTask := ecsPatterns.NewScheduledFargateTask(this, jsii.String("ScheduledFargateTask"), &ScheduledFargateTaskProps{
	Cluster: Cluster,
	ScheduledFargateTaskImageOptions: &ScheduledFargateTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		MemoryLimitMiB: jsii.Number(512),
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	PlatformVersion: ecs.FargatePlatformVersion_LATEST,
})

Additional Examples ​

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

Configure HTTPS on an ApplicationLoadBalancedFargateService ​

ts
import { HostedZone } from 'aws-cdk-lib/aws-route53';
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
import { SslPolicy } from 'aws-cdk-lib/aws-elasticloadbalancingv2';

const domainZone = HostedZone.fromLookup(this, 'Zone', { domainName: 'example.com' });
const certificate = Certificate.fromCertificateArn(this, 'Cert', 'arn:aws:acm:us-east-1:123456:certificate/abcdefg');

declare const vpc: ec2.Vpc;
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  vpc,
  cluster,
  minHealthyPercent: 100,
  certificate,
  sslPolicy: SslPolicy.RECOMMENDED,
  domainName: 'api.example.com',
  domainZone,
  redirectHTTP: true,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
});
python
from aws_cdk.aws_route53 import HostedZone
from aws_cdk.aws_certificatemanager import Certificate
from aws_cdk.aws_elasticloadbalancingv2 import SslPolicy

# vpc: ec2.Vpc
# cluster: ecs.Cluster


domain_zone = HostedZone.from_lookup(self, "Zone", domain_name="example.com")
certificate = Certificate.from_certificate_arn(self, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg")
load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    vpc=vpc,
    cluster=cluster,
    min_healthy_percent=100,
    certificate=certificate,
    ssl_policy=SslPolicy.RECOMMENDED,
    domain_name="api.example.com",
    domain_zone=domain_zone,
    redirect_http=True,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    )
)
java
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)
        .minHealthyPercent(100)
        .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();
csharp
using Amazon.CDK.AWS.Route53;
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;

Vpc vpc;
Cluster cluster;


var domainZone = HostedZone.FromLookup(this, "Zone", new HostedZoneProviderProps { DomainName = "example.com" });
var certificate = Certificate.FromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Vpc = vpc,
    Cluster = cluster,
    MinHealthyPercent = 100,
    Certificate = certificate,
    SslPolicy = SslPolicy.RECOMMENDED,
    DomainName = "api.example.com",
    DomainZone = domainZone,
    RedirectHTTP = true,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var vpc Vpc
var cluster Cluster


domainZone := awscdk.HostedZone_FromLookup(this, jsii.String("Zone"), &HostedZoneProviderProps{
	DomainName: jsii.String("example.com"),
})
certificate := awscdk.Certificate_FromCertificateArn(this, jsii.String("Cert"), jsii.String("arn:aws:acm:us-east-1:123456:certificate/abcdefg"))
loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Vpc: Vpc,
	Cluster: Cluster,
	MinHealthyPercent: jsii.Number(100),
	Certificate: Certificate,
	SslPolicy: awscdk.SslPolicy_RECOMMENDED,
	DomainName: jsii.String("api.example.com"),
	DomainZone: DomainZone,
	RedirectHTTP: jsii.Boolean(true),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
})

Set capacityProviderStrategies for ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
cluster.enableFargateCapacityProviders();

const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: 'FARGATE_SPOT',
      weight: 2,
      base: 0,
    },
    {
      capacityProvider: 'FARGATE',
      weight: 1,
      base: 1,
    },
  ],
});
python
# cluster: ecs.Cluster

cluster.enable_fargate_capacity_providers()

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider="FARGATE_SPOT",
        weight=2,
        base=0
    ), ecs.CapacityProviderStrategy(
        capacity_provider="FARGATE",
        weight=1,
        base=1
    )
    ]
)
java
Cluster cluster;

cluster.enableFargateCapacityProviders();

ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider("FARGATE_SPOT")
                .weight(2)
                .base(0)
                .build(), CapacityProviderStrategy.builder()
                .capacityProvider("FARGATE")
                .weight(1)
                .base(1)
                .build()))
        .build();
csharp
Cluster cluster;

cluster.EnableFargateCapacityProviders();

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = "FARGATE_SPOT",
        Weight = 2,
        Base = 0
    }, new CapacityProviderStrategy {
        CapacityProvider = "FARGATE",
        Weight = 1,
        Base = 1
    } }
});
go
var cluster Cluster

cluster.EnableFargateCapacityProviders()

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: jsii.String("FARGATE_SPOT"),
			Weight: jsii.Number(2),
			Base: jsii.Number(0),
		},
		&CapacityProviderStrategy{
			CapacityProvider: jsii.String("FARGATE"),
			Weight: jsii.Number(1),
			Base: jsii.Number(1),
		},
	},
})

Add Schedule-Based Auto-Scaling to an ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
});

const scalableTarget = loadBalancedFargateService.service.autoScaleTaskCount({
  minCapacity: 5,
  maxCapacity: 20,
});

scalableTarget.scaleOnSchedule('DaytimeScaleDown', {
  schedule: appscaling.Schedule.cron({ hour: '8', minute: '0'}),
  minCapacity: 1,
});

scalableTarget.scaleOnSchedule('EveningRushScaleUp', {
  schedule: appscaling.Schedule.cron({ hour: '20', minute: '0'}),
  minCapacity: 10,
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100
)

scalable_target = load_balanced_fargate_service.service.auto_scale_task_count(
    min_capacity=5,
    max_capacity=20
)

scalable_target.scale_on_schedule("DaytimeScaleDown",
    schedule=appscaling.Schedule.cron(hour="8", minute="0"),
    min_capacity=1
)

scalable_target.scale_on_schedule("EveningRushScaleUp",
    schedule=appscaling.Schedule.cron(hour="20", minute="0"),
    min_capacity=10
)
java
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())
        .minHealthyPercent(100)
        .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());
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100
});

var scalableTarget = loadBalancedFargateService.Service.AutoScaleTaskCount(new EnableScalingProps {
    MinCapacity = 5,
    MaxCapacity = 20
});

scalableTarget.ScaleOnSchedule("DaytimeScaleDown", new ScalingSchedule {
    Schedule = Schedule.Cron(new CronOptions { Hour = "8", Minute = "0" }),
    MinCapacity = 1
});

scalableTarget.ScaleOnSchedule("EveningRushScaleUp", new ScalingSchedule {
    Schedule = Schedule.Cron(new CronOptions { Hour = "20", Minute = "0" }),
    MinCapacity = 10
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
})

scalableTarget := loadBalancedFargateService.Service.AutoScaleTaskCount(&EnableScalingProps{
	MinCapacity: jsii.Number(5),
	MaxCapacity: jsii.Number(20),
})

scalableTarget.ScaleOnSchedule(jsii.String("DaytimeScaleDown"), &ScalingSchedule{
	Schedule: appscaling.Schedule_Cron(&CronOptions{
		Hour: jsii.String("8"),
		Minute: jsii.String("0"),
	}),
	MinCapacity: jsii.Number(1),
})

scalableTarget.ScaleOnSchedule(jsii.String("EveningRushScaleUp"), &ScalingSchedule{
	Schedule: appscaling.Schedule_*Cron(&CronOptions{
		Hour: jsii.String("20"),
		Minute: jsii.String("0"),
	}),
	MinCapacity: jsii.Number(10),
})

Add Metric-Based Auto-Scaling to an ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
});

const scalableTarget = loadBalancedFargateService.service.autoScaleTaskCount({
  minCapacity: 1,
  maxCapacity: 20,
});

scalableTarget.scaleOnCpuUtilization('CpuScaling', {
  targetUtilizationPercent: 50,
});

scalableTarget.scaleOnMemoryUtilization('MemoryScaling', {
  targetUtilizationPercent: 50,
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100
)

scalable_target = load_balanced_fargate_service.service.auto_scale_task_count(
    min_capacity=1,
    max_capacity=20
)

scalable_target.scale_on_cpu_utilization("CpuScaling",
    target_utilization_percent=50
)

scalable_target.scale_on_memory_utilization("MemoryScaling",
    target_utilization_percent=50
)
java
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())
        .minHealthyPercent(100)
        .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());
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100
});

var scalableTarget = loadBalancedFargateService.Service.AutoScaleTaskCount(new EnableScalingProps {
    MinCapacity = 1,
    MaxCapacity = 20
});

scalableTarget.ScaleOnCpuUtilization("CpuScaling", new CpuUtilizationScalingProps {
    TargetUtilizationPercent = 50
});

scalableTarget.ScaleOnMemoryUtilization("MemoryScaling", new MemoryUtilizationScalingProps {
    TargetUtilizationPercent = 50
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
})

scalableTarget := loadBalancedFargateService.Service.AutoScaleTaskCount(&EnableScalingProps{
	MinCapacity: jsii.Number(1),
	MaxCapacity: jsii.Number(20),
})

scalableTarget.ScaleOnCpuUtilization(jsii.String("CpuScaling"), &CpuUtilizationScalingProps{
	TargetUtilizationPercent: jsii.Number(50),
})

scalableTarget.ScaleOnMemoryUtilization(jsii.String("MemoryScaling"), &MemoryUtilizationScalingProps{
	TargetUtilizationPercent: jsii.Number(50),
})

Change the default Deployment Controller ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  deploymentController: {
    type: ecs.DeploymentControllerType.CODE_DEPLOY,
  },
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    deployment_controller=ecs.DeploymentController(
        type=ecs.DeploymentControllerType.CODE_DEPLOY
    )
)
java
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())
        .minHealthyPercent(100)
        .deploymentController(DeploymentController.builder()
                .type(DeploymentControllerType.CODE_DEPLOY)
                .build())
        .build();
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    DeploymentController = new DeploymentController {
        Type = DeploymentControllerType.CODE_DEPLOY
    }
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	DeploymentController: &DeploymentController{
		Type: ecs.DeploymentControllerType_CODE_DEPLOY,
	},
})

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.

ts
declare const cluster: ecs.Cluster;
const service = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  circuitBreaker: { rollback: true },
});
python
# cluster: ecs.Cluster

service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    circuit_breaker=ecs.DeploymentCircuitBreaker(rollback=True)
)
java
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())
        .minHealthyPercent(100)
        .circuitBreaker(DeploymentCircuitBreaker.builder().rollback(true).build())
        .build();
csharp
Cluster cluster;

var service = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    CircuitBreaker = new DeploymentCircuitBreaker { Rollback = true }
});
go
var cluster Cluster

service := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	CircuitBreaker: &DeploymentCircuitBreaker{
		Rollback: jsii.Boolean(true),
	},
})

Set deployment configuration on QueueProcessingService ​

ts
declare const cluster: ecs.Cluster;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  command: ["-c", "4", "amazon.com"],
  enableLogging: false,
  desiredTaskCount: 2,
  environment: {},
  maxScalingCapacity: 5,
  maxHealthyPercent: 200,
  minHealthyPercent: 66,
});
python
# cluster: ecs.Cluster

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    command=["-c", "4", "amazon.com"],
    enable_logging=False,
    desired_task_count=2,
    environment={},
    max_scaling_capacity=5,
    max_healthy_percent=200,
    min_healthy_percent=66
)
java
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();
csharp
Cluster cluster;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    Command = new [] { "-c", "4", "amazon.com" },
    EnableLogging = false,
    DesiredTaskCount = 2,
    Environment = new Dictionary<string, object> { },
    MaxScalingCapacity = 5,
    MaxHealthyPercent = 200,
    MinHealthyPercent = 66
});
go
var cluster Cluster

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	Command: []*string{
		jsii.String("-c"),
		jsii.String("4"),
		jsii.String("amazon.com"),
	},
	EnableLogging: jsii.Boolean(false),
	DesiredTaskCount: jsii.Number(2),
	Environment: map[string]interface{}{
	},
	MaxScalingCapacity: jsii.Number(5),
	MaxHealthyPercent: jsii.Number(200),
	MinHealthyPercent: jsii.Number(66),
})

Set taskSubnets and securityGroups for QueueProcessingFargateService ​

ts
declare const vpc: ec2.Vpc;
declare const securityGroup: ec2.SecurityGroup;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  securityGroups: [securityGroup],
  taskSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
});
python
# vpc: ec2.Vpc
# security_group: ec2.SecurityGroup

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    security_groups=[security_group],
    task_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_ISOLATED)
)
java
Vpc vpc;
SecurityGroup securityGroup;

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

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    SecurityGroups = new [] { securityGroup },
    TaskSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_ISOLATED }
});
go
var vpc Vpc
var securityGroup SecurityGroup

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	TaskSubnets: &SubnetSelection{
		SubnetType: ec2.SubnetType_PRIVATE_ISOLATED,
	},
})

Define tasks with public IPs for QueueProcessingFargateService ​

ts
declare const vpc: ec2.Vpc;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  assignPublicIp: true,
});
python
# vpc: ec2.Vpc

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    assign_public_ip=True
)
java
Vpc vpc;

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

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    AssignPublicIp = true
});
go
var vpc Vpc

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	AssignPublicIp: jsii.Boolean(true),
})

Define tasks with custom queue parameters for QueueProcessingFargateService ​

ts
declare const vpc: ec2.Vpc;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  maxReceiveCount: 42,
  retentionPeriod: Duration.days(7),
  visibilityTimeout: Duration.minutes(5),
});
python
# vpc: ec2.Vpc

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    max_receive_count=42,
    retention_period=Duration.days(7),
    visibility_timeout=Duration.minutes(5)
)
java
Vpc vpc;

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

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    MaxReceiveCount = 42,
    RetentionPeriod = Duration.Days(7),
    VisibilityTimeout = Duration.Minutes(5)
});
go
var vpc Vpc

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	MaxReceiveCount: jsii.Number(42),
	RetentionPeriod: awscdk.Duration_Days(jsii.Number(7)),
	VisibilityTimeout: awscdk.Duration_Minutes(jsii.Number(5)),
})

Set cooldown for QueueProcessingFargateService ​

The cooldown period is the amount of time to wait for a previous scaling activity to take effect. To specify something other than the default cooldown period of 300 seconds, use the cooldown parameter:

ts
declare const vpc: ec2.Vpc;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  assignPublicIp: true,
  cooldown: Duration.seconds(500),
});
python
# vpc: ec2.Vpc

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    assign_public_ip=True,
    cooldown=Duration.seconds(500)
)
java
Vpc vpc;

QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
        .vpc(vpc)
        .memoryLimitMiB(512)
        .image(ContainerImage.fromRegistry("test"))
        .minHealthyPercent(100)
        .assignPublicIp(true)
        .cooldown(Duration.seconds(500))
        .build();
csharp
Vpc vpc;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    AssignPublicIp = true,
    Cooldown = Duration.Seconds(500)
});
go
var vpc Vpc

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	AssignPublicIp: jsii.Boolean(true),
	Cooldown: awscdk.Duration_Seconds(jsii.Number(500)),
})

Set capacityProviderStrategies for QueueProcessingFargateService ​

ts
declare const cluster: ecs.Cluster;
cluster.enableFargateCapacityProviders();

const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: 'FARGATE_SPOT',
      weight: 2,
    },
    {
      capacityProvider: 'FARGATE',
      weight: 1,
    },
  ],
});
python
# cluster: ecs.Cluster

cluster.enable_fargate_capacity_providers()

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider="FARGATE_SPOT",
        weight=2
    ), ecs.CapacityProviderStrategy(
        capacity_provider="FARGATE",
        weight=1
    )
    ]
)
java
Cluster cluster;

cluster.enableFargateCapacityProviders();

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

cluster.EnableFargateCapacityProviders();

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = "FARGATE_SPOT",
        Weight = 2
    }, new CapacityProviderStrategy {
        CapacityProvider = "FARGATE",
        Weight = 1
    } }
});
go
var cluster Cluster

cluster.EnableFargateCapacityProviders()

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: jsii.String("FARGATE_SPOT"),
			Weight: jsii.Number(2),
		},
		&CapacityProviderStrategy{
			CapacityProvider: jsii.String("FARGATE"),
			Weight: jsii.Number(1),
		},
	},
})

Set a custom container-level Healthcheck for QueueProcessingFargateService ​

ts
declare const vpc: ec2.Vpc;
declare const securityGroup: ec2.SecurityGroup;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  healthCheck: {
    command: [ "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),
  },
});
python
# vpc: ec2.Vpc
# security_group: ec2.SecurityGroup

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    health_check=ecs.HealthCheck(
        command=["CMD-SHELL", "curl -f http://localhost/ || exit 1"],
        # the properties below are optional
        interval=Duration.minutes(30),
        retries=123,
        start_period=Duration.minutes(30),
        timeout=Duration.minutes(30)
    )
)
java
Vpc vpc;
SecurityGroup securityGroup;

QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
        .vpc(vpc)
        .memoryLimitMiB(512)
        .image(ContainerImage.fromRegistry("test"))
        .minHealthyPercent(100)
        .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();
csharp
Vpc vpc;
SecurityGroup securityGroup;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    HealthCheck = new HealthCheck {
        Command = new [] { "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)
    }
});
go
var vpc Vpc
var securityGroup SecurityGroup

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	HealthCheck: &HealthCheck{
		Command: []*string{
			jsii.String("CMD-SHELL"),
			jsii.String("curl -f http://localhost/ || exit 1"),
		},
		// the properties below are optional
		Interval: awscdk.Duration_Minutes(jsii.Number(30)),
		Retries: jsii.Number(123),
		StartPeriod: awscdk.Duration_*Minutes(jsii.Number(30)),
		Timeout: awscdk.Duration_*Minutes(jsii.Number(30)),
	},
})

Set capacityProviderStrategies for QueueProcessingEc2Service ​

ts
import * as autoscaling from 'aws-cdk-lib/aws-autoscaling';

const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 1 });
const cluster = new ecs.Cluster(this, 'EcsCluster', { vpc });
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'asg', {
  vpc,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
});
const capacityProvider = new ecs.AsgCapacityProvider(this, 'provider', {
  autoScalingGroup,
});
cluster.addAsgCapacityProvider(capacityProvider);

const queueProcessingEc2Service = new ecsPatterns.QueueProcessingEc2Service(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: capacityProvider.capacityProviderName,
    },
  ],
});
python
import aws_cdk.aws_autoscaling as autoscaling


vpc = ec2.Vpc(self, "Vpc", max_azs=1)
cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)
auto_scaling_group = autoscaling.AutoScalingGroup(self, "asg",
    vpc=vpc,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
    machine_image=ecs.EcsOptimizedImage.amazon_linux2()
)
capacity_provider = ecs.AsgCapacityProvider(self, "provider",
    auto_scaling_group=auto_scaling_group
)
cluster.add_asg_capacity_provider(capacity_provider)

queue_processing_ec2_service = ecs_patterns.QueueProcessingEc2Service(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider=capacity_provider.capacity_provider_name
    )
    ]
)
java
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);

QueueProcessingEc2Service queueProcessingEc2Service = QueueProcessingEc2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .memoryLimitMiB(512)
        .image(ContainerImage.fromRegistry("test"))
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider(capacityProvider.getCapacityProviderName())
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.AutoScaling;


var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var autoScalingGroup = new AutoScalingGroup(this, "asg", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
    MachineImage = EcsOptimizedImage.AmazonLinux2()
});
var capacityProvider = new AsgCapacityProvider(this, "provider", new AsgCapacityProviderProps {
    AutoScalingGroup = autoScalingGroup
});
cluster.AddAsgCapacityProvider(capacityProvider);

var queueProcessingEc2Service = new QueueProcessingEc2Service(this, "Service", new QueueProcessingEc2ServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = capacityProvider.CapacityProviderName
    } }
});
go
import autoscaling "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(1),
})
cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	Vpc: Vpc,
})
autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("asg"), &AutoScalingGroupProps{
	Vpc: Vpc,
	InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_MICRO),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux2(),
})
capacityProvider := ecs.NewAsgCapacityProvider(this, jsii.String("provider"), &AsgCapacityProviderProps{
	AutoScalingGroup: AutoScalingGroup,
})
cluster.AddAsgCapacityProvider(capacityProvider)

queueProcessingEc2Service := ecsPatterns.NewQueueProcessingEc2Service(this, jsii.String("Service"), &QueueProcessingEc2ServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: capacityProvider.CapacityProviderName,
		},
	},
})

Select specific vpc subnets for ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  taskSubnets: {
    subnets: [ec2.Subnet.fromSubnetId(this, 'subnet', 'VpcISOLATEDSubnet1Subnet80F07FA0')],
  },
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    task_subnets=ec2.SubnetSelection(
        subnets=[ec2.Subnet.from_subnet_id(self, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")]
    )
)
java
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())
        .minHealthyPercent(100)
        .taskSubnets(SubnetSelection.builder()
                .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                .build())
        .build();
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    TaskSubnets = new SubnetSelection {
        Subnets = new [] { Subnet.FromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0") }
    }
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	TaskSubnets: &SubnetSelection{
		Subnets: []ISubnet{
			ec2.Subnet_FromSubnetId(this, jsii.String("subnet"), jsii.String("VpcISOLATEDSubnet1Subnet80F07FA0")),
		},
	},
})

Select idleTimeout for ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  idleTimeout: Duration.seconds(120),
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    idle_timeout=Duration.seconds(120)
)
java
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())
        .minHealthyPercent(100)
        .idleTimeout(Duration.seconds(120))
        .build();
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    IdleTimeout = Duration.Seconds(120)
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	IdleTimeout: awscdk.Duration_Seconds(jsii.Number(120)),
})

Select idleTimeout for ApplicationMultipleTargetGroupsFargateService ​

ts
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
import { InstanceType } from 'aws-cdk-lib/aws-ec2';
import { Cluster, ContainerImage } from 'aws-cdk-lib/aws-ecs';
import { ApplicationProtocol, SslPolicy } from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import { PublicHostedZone } from 'aws-cdk-lib/aws-route53';
const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 1 });
const loadBalancedFargateService = new ecsPatterns.ApplicationMultipleTargetGroupsFargateService(this, 'myService', {
  cluster: new ecs.Cluster(this, 'EcsCluster', { vpc }),
  memoryLimitMiB: 256,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  enableExecuteCommand: true,
  loadBalancers: [
    {
      name: 'lb',
      idleTimeout: Duration.seconds(400),
      domainName: 'api.example.com',
      domainZone: new PublicHostedZone(this, 'HostedZone', { zoneName: 'example.com' }),
      listeners: [
        {
          name: 'listener',
          protocol: ApplicationProtocol.HTTPS,
          certificate: Certificate.fromCertificateArn(this, 'Cert', 'helloworld'),
          sslPolicy: SslPolicy.TLS12_EXT,
        },
      ],
    },
    {
      name: 'lb2',
      idleTimeout: Duration.seconds(120),
      domainName: 'frontend.com',
      domainZone: new PublicHostedZone(this, 'HostedZone', { zoneName: 'frontend.com' }),
      listeners: [
        {
          name: 'listener2',
          protocol: ApplicationProtocol.HTTPS,
          certificate: Certificate.fromCertificateArn(this, 'Cert2', 'helloworld'),
          sslPolicy: SslPolicy.TLS12_EXT,
        },
      ],
    },
  ],
  targetGroups: [
    {
      containerPort: 80,
      listener: 'listener',
    },
    {
      containerPort: 90,
      pathPattern: 'a/b/c',
      priority: 10,
      listener: 'listener',
    },
    {
      containerPort: 443,
      listener: 'listener2',
    },
    {
      containerPort: 80,
      pathPattern: 'a/b/c',
      priority: 10,
      listener: 'listener2',
    },
  ],
});
python
from aws_cdk.aws_certificatemanager import Certificate
from aws_cdk.aws_ec2 import InstanceType
from aws_cdk.aws_ecs import Cluster, ContainerImage
from aws_cdk.aws_elasticloadbalancingv2 import ApplicationProtocol, SslPolicy
from aws_cdk.aws_route53 import PublicHostedZone

vpc = ec2.Vpc(self, "Vpc", max_azs=1)
load_balanced_fargate_service = ecs_patterns.ApplicationMultipleTargetGroupsFargateService(self, "myService",
    cluster=ecs.Cluster(self, "EcsCluster", vpc=vpc),
    memory_limit_mi_b=256,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageProps(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    enable_execute_command=True,
    load_balancers=[ecsPatterns.ApplicationLoadBalancerProps(
        name="lb",
        idle_timeout=Duration.seconds(400),
        domain_name="api.example.com",
        domain_zone=PublicHostedZone(self, "HostedZone", zone_name="example.com"),
        listeners=[ecsPatterns.ApplicationListenerProps(
            name="listener",
            protocol=ApplicationProtocol.HTTPS,
            certificate=Certificate.from_certificate_arn(self, "Cert", "helloworld"),
            ssl_policy=SslPolicy.TLS12_EXT
        )
        ]
    ), ecsPatterns.ApplicationLoadBalancerProps(
        name="lb2",
        idle_timeout=Duration.seconds(120),
        domain_name="frontend.com",
        domain_zone=PublicHostedZone(self, "HostedZone", zone_name="frontend.com"),
        listeners=[ecsPatterns.ApplicationListenerProps(
            name="listener2",
            protocol=ApplicationProtocol.HTTPS,
            certificate=Certificate.from_certificate_arn(self, "Cert2", "helloworld"),
            ssl_policy=SslPolicy.TLS12_EXT
        )
        ]
    )
    ],
    target_groups=[ecsPatterns.ApplicationTargetProps(
        container_port=80,
        listener="listener"
    ), ecsPatterns.ApplicationTargetProps(
        container_port=90,
        path_pattern="a/b/c",
        priority=10,
        listener="listener"
    ), ecsPatterns.ApplicationTargetProps(
        container_port=443,
        listener="listener2"
    ), ecsPatterns.ApplicationTargetProps(
        container_port=80,
        path_pattern="a/b/c",
        priority=10,
        listener="listener2"
    )
    ]
)
java
import software.amazon.awscdk.services.certificatemanager.Certificate;
import software.amazon.awscdk.services.ec2.InstanceType;
import software.amazon.awscdk.services.ecs.Cluster;
import software.amazon.awscdk.services.ecs.ContainerImage;
import software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationProtocol;
import software.amazon.awscdk.services.elasticloadbalancingv2.SslPolicy;
import software.amazon.awscdk.services.route53.PublicHostedZone;

Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
ApplicationMultipleTargetGroupsFargateService loadBalancedFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, "myService")
        .cluster(Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build())
        .memoryLimitMiB(256)
        .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .enableExecuteCommand(true)
        .loadBalancers(List.of(ApplicationLoadBalancerProps.builder()
                .name("lb")
                .idleTimeout(Duration.seconds(400))
                .domainName("api.example.com")
                .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("example.com").build())
                .listeners(List.of(ApplicationListenerProps.builder()
                        .name("listener")
                        .protocol(ApplicationProtocol.HTTPS)
                        .certificate(Certificate.fromCertificateArn(this, "Cert", "helloworld"))
                        .sslPolicy(SslPolicy.TLS12_EXT)
                        .build()))
                .build(), ApplicationLoadBalancerProps.builder()
                .name("lb2")
                .idleTimeout(Duration.seconds(120))
                .domainName("frontend.com")
                .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("frontend.com").build())
                .listeners(List.of(ApplicationListenerProps.builder()
                        .name("listener2")
                        .protocol(ApplicationProtocol.HTTPS)
                        .certificate(Certificate.fromCertificateArn(this, "Cert2", "helloworld"))
                        .sslPolicy(SslPolicy.TLS12_EXT)
                        .build()))
                .build()))
        .targetGroups(List.of(ApplicationTargetProps.builder()
                .containerPort(80)
                .listener("listener")
                .build(), ApplicationTargetProps.builder()
                .containerPort(90)
                .pathPattern("a/b/c")
                .priority(10)
                .listener("listener")
                .build(), ApplicationTargetProps.builder()
                .containerPort(443)
                .listener("listener2")
                .build(), ApplicationTargetProps.builder()
                .containerPort(80)
                .pathPattern("a/b/c")
                .priority(10)
                .listener("listener2")
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Amazon.CDK.AWS.Route53;

var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var loadBalancedFargateService = new ApplicationMultipleTargetGroupsFargateService(this, "myService", new ApplicationMultipleTargetGroupsFargateServiceProps {
    Cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc }),
    MemoryLimitMiB = 256,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    EnableExecuteCommand = true,
    LoadBalancers = new [] { new ApplicationLoadBalancerProps {
        Name = "lb",
        IdleTimeout = Duration.Seconds(400),
        DomainName = "api.example.com",
        DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "example.com" }),
        Listeners = new [] { new ApplicationListenerProps {
            Name = "listener",
            Protocol = ApplicationProtocol.HTTPS,
            Certificate = Certificate.FromCertificateArn(this, "Cert", "helloworld"),
            SslPolicy = SslPolicy.TLS12_EXT
        } }
    }, new ApplicationLoadBalancerProps {
        Name = "lb2",
        IdleTimeout = Duration.Seconds(120),
        DomainName = "frontend.com",
        DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "frontend.com" }),
        Listeners = new [] { new ApplicationListenerProps {
            Name = "listener2",
            Protocol = ApplicationProtocol.HTTPS,
            Certificate = Certificate.FromCertificateArn(this, "Cert2", "helloworld"),
            SslPolicy = SslPolicy.TLS12_EXT
        } }
    } },
    TargetGroups = new [] { new ApplicationTargetProps {
        ContainerPort = 80,
        Listener = "listener"
    }, new ApplicationTargetProps {
        ContainerPort = 90,
        PathPattern = "a/b/c",
        Priority = 10,
        Listener = "listener"
    }, new ApplicationTargetProps {
        ContainerPort = 443,
        Listener = "listener2"
    }, new ApplicationTargetProps {
        ContainerPort = 80,
        PathPattern = "a/b/c",
        Priority = 10,
        Listener = "listener2"
    } }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(1),
})
loadBalancedFargateService := ecsPatterns.NewApplicationMultipleTargetGroupsFargateService(this, jsii.String("myService"), &ApplicationMultipleTargetGroupsFargateServiceProps{
	Cluster: ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
		Vpc: *Vpc,
	}),
	MemoryLimitMiB: jsii.Number(256),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageProps{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	EnableExecuteCommand: jsii.Boolean(true),
	LoadBalancers: []ApplicationLoadBalancerProps{
		&ApplicationLoadBalancerProps{
			Name: jsii.String("lb"),
			IdleTimeout: awscdk.Duration_Seconds(jsii.Number(400)),
			DomainName: jsii.String("api.example.com"),
			DomainZone: awscdk.NewPublicHostedZone(this, jsii.String("HostedZone"), &PublicHostedZoneProps{
				ZoneName: jsii.String("example.com"),
			}),
			Listeners: []ApplicationListenerProps{
				&ApplicationListenerProps{
					Name: jsii.String("listener"),
					Protocol: awscdk.ApplicationProtocol_HTTPS,
					Certificate: awscdk.Certificate_FromCertificateArn(this, jsii.String("Cert"), jsii.String("helloworld")),
					SslPolicy: awscdk.SslPolicy_TLS12_EXT,
				},
			},
		},
		&ApplicationLoadBalancerProps{
			Name: jsii.String("lb2"),
			IdleTimeout: awscdk.Duration_*Seconds(jsii.Number(120)),
			DomainName: jsii.String("frontend.com"),
			DomainZone: awscdk.NewPublicHostedZone(this, jsii.String("HostedZone"), &PublicHostedZoneProps{
				ZoneName: jsii.String("frontend.com"),
			}),
			Listeners: []ApplicationListenerProps{
				&ApplicationListenerProps{
					Name: jsii.String("listener2"),
					Protocol: awscdk.ApplicationProtocol_HTTPS,
					Certificate: awscdk.Certificate_*FromCertificateArn(this, jsii.String("Cert2"), jsii.String("helloworld")),
					SslPolicy: awscdk.SslPolicy_TLS12_EXT,
				},
			},
		},
	},
	TargetGroups: []ApplicationTargetProps{
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(80),
			Listener: jsii.String("listener"),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(90),
			PathPattern: jsii.String("a/b/c"),
			Priority: jsii.Number(10),
			Listener: jsii.String("listener"),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(443),
			Listener: jsii.String("listener2"),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(80),
			PathPattern: jsii.String("a/b/c"),
			Priority: jsii.Number(10),
			Listener: jsii.String("listener2"),
		},
	},
})

Set health checks for ApplicationMultipleTargetGroupsFargateService ​

ts
import { Certificate } from 'aws-cdk-lib/aws-certificatemanager';
import { InstanceType } from 'aws-cdk-lib/aws-ec2';
import { Cluster, ContainerImage } from 'aws-cdk-lib/aws-ecs';
import { ApplicationProtocol,Protocol, SslPolicy } from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import { PublicHostedZone } from 'aws-cdk-lib/aws-route53';
const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 1 });

const loadBalancedFargateService = new ecsPatterns.ApplicationMultipleTargetGroupsFargateService(this, 'myService', {
  cluster: new ecs.Cluster(this, 'EcsCluster', { vpc }),
  memoryLimitMiB: 256,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  enableExecuteCommand: true,
  loadBalancers: [
    {
      name: 'lb',
      idleTimeout: Duration.seconds(400),
      domainName: 'api.example.com',
      domainZone: new PublicHostedZone(this, 'HostedZone', { zoneName: 'example.com' }),
      listeners: [
        {
          name: 'listener',
          protocol: ApplicationProtocol.HTTPS,
          certificate: Certificate.fromCertificateArn(this, 'Cert', 'helloworld'),
          sslPolicy: SslPolicy.TLS12_EXT,
        },
      ],
    },
    {
      name: 'lb2',
      idleTimeout: Duration.seconds(120),
      domainName: 'frontend.com',
      domainZone: new PublicHostedZone(this, 'HostedZone', { zoneName: 'frontend.com' }),
      listeners: [
        {
          name: 'listener2',
          protocol: ApplicationProtocol.HTTPS,
          certificate: Certificate.fromCertificateArn(this, 'Cert2', 'helloworld'),
          sslPolicy: SslPolicy.TLS12_EXT,
        },
      ],
    },
  ],
  targetGroups: [
    {
      containerPort: 80,
      listener: 'listener',
    },
    {
      containerPort: 90,
      pathPattern: 'a/b/c',
      priority: 10,
      listener: 'listener',
    },
    {
      containerPort: 443,
      listener: 'listener2',
    },
    {
      containerPort: 80,
      pathPattern: 'a/b/c',
      priority: 10,
      listener: 'listener2',
    },
  ],
});

loadBalancedFargateService.targetGroups[0].configureHealthCheck({
  port: '8050',
  protocol: Protocol.HTTP,
  healthyThresholdCount: 2,
  unhealthyThresholdCount: 2,
  timeout: Duration.seconds(10),
  interval: Duration.seconds(30),
  healthyHttpCodes: '200',
});


loadBalancedFargateService.targetGroups[1].configureHealthCheck({
  port: '8050',
  protocol: Protocol.HTTP,
  healthyThresholdCount: 2,
  unhealthyThresholdCount: 2,
  timeout: Duration.seconds(10),
  interval: Duration.seconds(30),
  healthyHttpCodes: '200',
});
python
from aws_cdk.aws_certificatemanager import Certificate
from aws_cdk.aws_ec2 import InstanceType
from aws_cdk.aws_ecs import Cluster, ContainerImage
from aws_cdk.aws_elasticloadbalancingv2 import ApplicationProtocol, Protocol, SslPolicy
from aws_cdk.aws_route53 import PublicHostedZone

vpc = ec2.Vpc(self, "Vpc", max_azs=1)

load_balanced_fargate_service = ecs_patterns.ApplicationMultipleTargetGroupsFargateService(self, "myService",
    cluster=ecs.Cluster(self, "EcsCluster", vpc=vpc),
    memory_limit_mi_b=256,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageProps(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    enable_execute_command=True,
    load_balancers=[ecsPatterns.ApplicationLoadBalancerProps(
        name="lb",
        idle_timeout=Duration.seconds(400),
        domain_name="api.example.com",
        domain_zone=PublicHostedZone(self, "HostedZone", zone_name="example.com"),
        listeners=[ecsPatterns.ApplicationListenerProps(
            name="listener",
            protocol=ApplicationProtocol.HTTPS,
            certificate=Certificate.from_certificate_arn(self, "Cert", "helloworld"),
            ssl_policy=SslPolicy.TLS12_EXT
        )
        ]
    ), ecsPatterns.ApplicationLoadBalancerProps(
        name="lb2",
        idle_timeout=Duration.seconds(120),
        domain_name="frontend.com",
        domain_zone=PublicHostedZone(self, "HostedZone", zone_name="frontend.com"),
        listeners=[ecsPatterns.ApplicationListenerProps(
            name="listener2",
            protocol=ApplicationProtocol.HTTPS,
            certificate=Certificate.from_certificate_arn(self, "Cert2", "helloworld"),
            ssl_policy=SslPolicy.TLS12_EXT
        )
        ]
    )
    ],
    target_groups=[ecsPatterns.ApplicationTargetProps(
        container_port=80,
        listener="listener"
    ), ecsPatterns.ApplicationTargetProps(
        container_port=90,
        path_pattern="a/b/c",
        priority=10,
        listener="listener"
    ), ecsPatterns.ApplicationTargetProps(
        container_port=443,
        listener="listener2"
    ), ecsPatterns.ApplicationTargetProps(
        container_port=80,
        path_pattern="a/b/c",
        priority=10,
        listener="listener2"
    )
    ]
)

load_balanced_fargate_service.target_groups[0].configure_health_check(
    port="8050",
    protocol=Protocol.HTTP,
    healthy_threshold_count=2,
    unhealthy_threshold_count=2,
    timeout=Duration.seconds(10),
    interval=Duration.seconds(30),
    healthy_http_codes="200"
)

load_balanced_fargate_service.target_groups[1].configure_health_check(
    port="8050",
    protocol=Protocol.HTTP,
    healthy_threshold_count=2,
    unhealthy_threshold_count=2,
    timeout=Duration.seconds(10),
    interval=Duration.seconds(30),
    healthy_http_codes="200"
)
java
import software.amazon.awscdk.services.certificatemanager.Certificate;
import software.amazon.awscdk.services.ec2.InstanceType;
import software.amazon.awscdk.services.ecs.Cluster;
import software.amazon.awscdk.services.ecs.ContainerImage;
import software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationProtocol;
import software.amazon.awscdk.services.elasticloadbalancingv2.Protocol;
import software.amazon.awscdk.services.elasticloadbalancingv2.SslPolicy;
import software.amazon.awscdk.services.route53.PublicHostedZone;

Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();

ApplicationMultipleTargetGroupsFargateService loadBalancedFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, "myService")
        .cluster(Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build())
        .memoryLimitMiB(256)
        .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .enableExecuteCommand(true)
        .loadBalancers(List.of(ApplicationLoadBalancerProps.builder()
                .name("lb")
                .idleTimeout(Duration.seconds(400))
                .domainName("api.example.com")
                .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("example.com").build())
                .listeners(List.of(ApplicationListenerProps.builder()
                        .name("listener")
                        .protocol(ApplicationProtocol.HTTPS)
                        .certificate(Certificate.fromCertificateArn(this, "Cert", "helloworld"))
                        .sslPolicy(SslPolicy.TLS12_EXT)
                        .build()))
                .build(), ApplicationLoadBalancerProps.builder()
                .name("lb2")
                .idleTimeout(Duration.seconds(120))
                .domainName("frontend.com")
                .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("frontend.com").build())
                .listeners(List.of(ApplicationListenerProps.builder()
                        .name("listener2")
                        .protocol(ApplicationProtocol.HTTPS)
                        .certificate(Certificate.fromCertificateArn(this, "Cert2", "helloworld"))
                        .sslPolicy(SslPolicy.TLS12_EXT)
                        .build()))
                .build()))
        .targetGroups(List.of(ApplicationTargetProps.builder()
                .containerPort(80)
                .listener("listener")
                .build(), ApplicationTargetProps.builder()
                .containerPort(90)
                .pathPattern("a/b/c")
                .priority(10)
                .listener("listener")
                .build(), ApplicationTargetProps.builder()
                .containerPort(443)
                .listener("listener2")
                .build(), ApplicationTargetProps.builder()
                .containerPort(80)
                .pathPattern("a/b/c")
                .priority(10)
                .listener("listener2")
                .build()))
        .build();

loadBalancedFargateService.targetGroups[0].configureHealthCheck(HealthCheck.builder()
        .port("8050")
        .protocol(Protocol.HTTP)
        .healthyThresholdCount(2)
        .unhealthyThresholdCount(2)
        .timeout(Duration.seconds(10))
        .interval(Duration.seconds(30))
        .healthyHttpCodes("200")
        .build());

loadBalancedFargateService.targetGroups[1].configureHealthCheck(HealthCheck.builder()
        .port("8050")
        .protocol(Protocol.HTTP)
        .healthyThresholdCount(2)
        .unhealthyThresholdCount(2)
        .timeout(Duration.seconds(10))
        .interval(Duration.seconds(30))
        .healthyHttpCodes("200")
        .build());
csharp
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Amazon.CDK.AWS.Route53;

var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });

var loadBalancedFargateService = new ApplicationMultipleTargetGroupsFargateService(this, "myService", new ApplicationMultipleTargetGroupsFargateServiceProps {
    Cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc }),
    MemoryLimitMiB = 256,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    EnableExecuteCommand = true,
    LoadBalancers = new [] { new ApplicationLoadBalancerProps {
        Name = "lb",
        IdleTimeout = Duration.Seconds(400),
        DomainName = "api.example.com",
        DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "example.com" }),
        Listeners = new [] { new ApplicationListenerProps {
            Name = "listener",
            Protocol = ApplicationProtocol.HTTPS,
            Certificate = Certificate.FromCertificateArn(this, "Cert", "helloworld"),
            SslPolicy = SslPolicy.TLS12_EXT
        } }
    }, new ApplicationLoadBalancerProps {
        Name = "lb2",
        IdleTimeout = Duration.Seconds(120),
        DomainName = "frontend.com",
        DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "frontend.com" }),
        Listeners = new [] { new ApplicationListenerProps {
            Name = "listener2",
            Protocol = ApplicationProtocol.HTTPS,
            Certificate = Certificate.FromCertificateArn(this, "Cert2", "helloworld"),
            SslPolicy = SslPolicy.TLS12_EXT
        } }
    } },
    TargetGroups = new [] { new ApplicationTargetProps {
        ContainerPort = 80,
        Listener = "listener"
    }, new ApplicationTargetProps {
        ContainerPort = 90,
        PathPattern = "a/b/c",
        Priority = 10,
        Listener = "listener"
    }, new ApplicationTargetProps {
        ContainerPort = 443,
        Listener = "listener2"
    }, new ApplicationTargetProps {
        ContainerPort = 80,
        PathPattern = "a/b/c",
        Priority = 10,
        Listener = "listener2"
    } }
});

loadBalancedFargateService.TargetGroups[0].ConfigureHealthCheck(new HealthCheck {
    Port = "8050",
    Protocol = Protocol.HTTP,
    HealthyThresholdCount = 2,
    UnhealthyThresholdCount = 2,
    Timeout = Duration.Seconds(10),
    Interval = Duration.Seconds(30),
    HealthyHttpCodes = "200"
});

loadBalancedFargateService.TargetGroups[1].ConfigureHealthCheck(new HealthCheck {
    Port = "8050",
    Protocol = Protocol.HTTP,
    HealthyThresholdCount = 2,
    UnhealthyThresholdCount = 2,
    Timeout = Duration.Seconds(10),
    Interval = Duration.Seconds(30),
    HealthyHttpCodes = "200"
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(1),
})

loadBalancedFargateService := ecsPatterns.NewApplicationMultipleTargetGroupsFargateService(this, jsii.String("myService"), &ApplicationMultipleTargetGroupsFargateServiceProps{
	Cluster: ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
		Vpc: *Vpc,
	}),
	MemoryLimitMiB: jsii.Number(256),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageProps{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	EnableExecuteCommand: jsii.Boolean(true),
	LoadBalancers: []ApplicationLoadBalancerProps{
		&ApplicationLoadBalancerProps{
			Name: jsii.String("lb"),
			IdleTimeout: awscdk.Duration_Seconds(jsii.Number(400)),
			DomainName: jsii.String("api.example.com"),
			DomainZone: awscdk.NewPublicHostedZone(this, jsii.String("HostedZone"), &PublicHostedZoneProps{
				ZoneName: jsii.String("example.com"),
			}),
			Listeners: []ApplicationListenerProps{
				&ApplicationListenerProps{
					Name: jsii.String("listener"),
					Protocol: awscdk.ApplicationProtocol_HTTPS,
					Certificate: awscdk.Certificate_FromCertificateArn(this, jsii.String("Cert"), jsii.String("helloworld")),
					SslPolicy: awscdk.SslPolicy_TLS12_EXT,
				},
			},
		},
		&ApplicationLoadBalancerProps{
			Name: jsii.String("lb2"),
			IdleTimeout: awscdk.Duration_*Seconds(jsii.Number(120)),
			DomainName: jsii.String("frontend.com"),
			DomainZone: awscdk.NewPublicHostedZone(this, jsii.String("HostedZone"), &PublicHostedZoneProps{
				ZoneName: jsii.String("frontend.com"),
			}),
			Listeners: []ApplicationListenerProps{
				&ApplicationListenerProps{
					Name: jsii.String("listener2"),
					Protocol: awscdk.ApplicationProtocol_HTTPS,
					Certificate: awscdk.Certificate_*FromCertificateArn(this, jsii.String("Cert2"), jsii.String("helloworld")),
					SslPolicy: awscdk.SslPolicy_TLS12_EXT,
				},
			},
		},
	},
	TargetGroups: []ApplicationTargetProps{
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(80),
			Listener: jsii.String("listener"),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(90),
			PathPattern: jsii.String("a/b/c"),
			Priority: jsii.Number(10),
			Listener: jsii.String("listener"),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(443),
			Listener: jsii.String("listener2"),
		},
		&ApplicationTargetProps{
			ContainerPort: jsii.Number(80),
			PathPattern: jsii.String("a/b/c"),
			Priority: jsii.Number(10),
			Listener: jsii.String("listener2"),
		},
	},
})

loadBalancedFargateService.TargetGroups[0].ConfigureHealthCheck(&HealthCheck{
	Port: jsii.String("8050"),
	Protocol: awscdk.Protocol_HTTP,
	HealthyThresholdCount: jsii.Number(2),
	UnhealthyThresholdCount: jsii.Number(2),
	Timeout: awscdk.Duration_*Seconds(jsii.Number(10)),
	Interval: awscdk.Duration_*Seconds(jsii.Number(30)),
	HealthyHttpCodes: jsii.String("200"),
})

loadBalancedFargateService.TargetGroups[1].ConfigureHealthCheck(&HealthCheck{
	Port: jsii.String("8050"),
	Protocol: awscdk.Protocol_HTTP,
	HealthyThresholdCount: jsii.Number(2),
	UnhealthyThresholdCount: jsii.Number(2),
	Timeout: awscdk.Duration_*Seconds(jsii.Number(10)),
	Interval: awscdk.Duration_*Seconds(jsii.Number(30)),
	HealthyHttpCodes: jsii.String("200"),
})

Set runtimePlatform for ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
const applicationLoadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
  runtimePlatform: {
    cpuArchitecture: ecs.CpuArchitecture.ARM64,
    operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
  },
});
python
# cluster: ecs.Cluster

application_load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    runtime_platform=ecs.RuntimePlatform(
        cpu_architecture=ecs.CpuArchitecture.ARM64,
        operating_system_family=ecs.OperatingSystemFamily.LINUX
    )
)
java
Cluster cluster;

ApplicationLoadBalancedFargateService applicationLoadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .memoryLimitMiB(512)
        .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .runtimePlatform(RuntimePlatform.builder()
                .cpuArchitecture(CpuArchitecture.ARM64)
                .operatingSystemFamily(OperatingSystemFamily.LINUX)
                .build())
        .build();
csharp
Cluster cluster;

var applicationLoadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    RuntimePlatform = new RuntimePlatform {
        CpuArchitecture = CpuArchitecture.ARM64,
        OperatingSystemFamily = OperatingSystemFamily.LINUX
    }
});
go
var cluster Cluster

applicationLoadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	RuntimePlatform: &RuntimePlatform{
		CpuArchitecture: ecs.CpuArchitecture_ARM64(),
		OperatingSystemFamily: ecs.OperatingSystemFamily_LINUX(),
	},
})

Customize Container Name for ScheduledFargateTask ​

ts
declare const cluster: ecs.Cluster;
const scheduledFargateTask = new ecsPatterns.ScheduledFargateTask(this, 'ScheduledFargateTask', {
  cluster,
  scheduledFargateTaskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
    containerName: 'customContainerName',
    memoryLimitMiB: 512,
  },
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  platformVersion: ecs.FargatePlatformVersion.LATEST,
});
python
# cluster: ecs.Cluster

scheduled_fargate_task = ecs_patterns.ScheduledFargateTask(self, "ScheduledFargateTask",
    cluster=cluster,
    scheduled_fargate_task_image_options=ecsPatterns.ScheduledFargateTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        container_name="customContainerName",
        memory_limit_mi_b=512
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    platform_version=ecs.FargatePlatformVersion.LATEST
)
java
Cluster cluster;

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

var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
    Cluster = cluster,
    ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        ContainerName = "customContainerName",
        MemoryLimitMiB = 512
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    PlatformVersion = FargatePlatformVersion.LATEST
});
go
var cluster Cluster

scheduledFargateTask := ecsPatterns.NewScheduledFargateTask(this, jsii.String("ScheduledFargateTask"), &ScheduledFargateTaskProps{
	Cluster: Cluster,
	ScheduledFargateTaskImageOptions: &ScheduledFargateTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		ContainerName: jsii.String("customContainerName"),
		MemoryLimitMiB: jsii.Number(512),
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	PlatformVersion: ecs.FargatePlatformVersion_LATEST,
})

Customize Container Name for ScheduledEc2Task ​

ts
declare const cluster: ecs.Cluster;
const ecsScheduledTask = new ecsPatterns.ScheduledEc2Task(this, 'ScheduledTask', {
    cluster,
    scheduledEc2TaskImageOptions: {
        image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
        containerName: 'customContainerName',
        memoryLimitMiB: 256,
        environment: { name: 'TRIGGER', value: 'CloudWatch Events' },
    },
    schedule: appscaling.Schedule.expression('rate(1 minute)'),
    enabled: true,
    ruleName: 'sample-scheduled-task-rule',
});
python
# cluster: ecs.Cluster

ecs_scheduled_task = ecs_patterns.ScheduledEc2Task(self, "ScheduledTask",
    cluster=cluster,
    scheduled_ec2_task_image_options=ecsPatterns.ScheduledEc2TaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        container_name="customContainerName",
        memory_limit_mi_b=256,
        environment={"name": "TRIGGER", "value": "CloudWatch Events"}
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    enabled=True,
    rule_name="sample-scheduled-task-rule"
)
java
Cluster cluster;

ScheduledEc2Task ecsScheduledTask = ScheduledEc2Task.Builder.create(this, "ScheduledTask")
        .cluster(cluster)
        .scheduledEc2TaskImageOptions(ScheduledEc2TaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .containerName("customContainerName")
                .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();
csharp
Cluster cluster;

var ecsScheduledTask = new ScheduledEc2Task(this, "ScheduledTask", new ScheduledEc2TaskProps {
    Cluster = cluster,
    ScheduledEc2TaskImageOptions = new ScheduledEc2TaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        ContainerName = "customContainerName",
        MemoryLimitMiB = 256,
        Environment = new Dictionary<string, string> { { "name", "TRIGGER" }, { "value", "CloudWatch Events" } }
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    Enabled = true,
    RuleName = "sample-scheduled-task-rule"
});
go
var cluster Cluster

ecsScheduledTask := ecsPatterns.NewScheduledEc2Task(this, jsii.String("ScheduledTask"), &ScheduledEc2TaskProps{
	Cluster: Cluster,
	ScheduledEc2TaskImageOptions: &ScheduledEc2TaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		ContainerName: jsii.String("customContainerName"),
		MemoryLimitMiB: jsii.Number(256),
		Environment: map[string]*string{
			"name": jsii.String("TRIGGER"),
			"value": jsii.String("CloudWatch Events"),
		},
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	Enabled: jsii.Boolean(true),
	RuleName: jsii.String("sample-scheduled-task-rule"),
})

Set PlatformVersion for ScheduledFargateTask ​

ts
declare const cluster: ecs.Cluster;
const scheduledFargateTask = new ecsPatterns.ScheduledFargateTask(this, 'ScheduledFargateTask', {
  cluster,
  scheduledFargateTaskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
    memoryLimitMiB: 512,
  },
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  platformVersion: ecs.FargatePlatformVersion.VERSION1_4,
});
python
# cluster: ecs.Cluster

scheduled_fargate_task = ecs_patterns.ScheduledFargateTask(self, "ScheduledFargateTask",
    cluster=cluster,
    scheduled_fargate_task_image_options=ecsPatterns.ScheduledFargateTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        memory_limit_mi_b=512
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    platform_version=ecs.FargatePlatformVersion.VERSION1_4
)
java
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();
csharp
Cluster cluster;

var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
    Cluster = cluster,
    ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        MemoryLimitMiB = 512
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    PlatformVersion = FargatePlatformVersion.VERSION1_4
});
go
var cluster Cluster

scheduledFargateTask := ecsPatterns.NewScheduledFargateTask(this, jsii.String("ScheduledFargateTask"), &ScheduledFargateTaskProps{
	Cluster: Cluster,
	ScheduledFargateTaskImageOptions: &ScheduledFargateTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		MemoryLimitMiB: jsii.Number(512),
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	PlatformVersion: ecs.FargatePlatformVersion_VERSION1_4,
})

Set SecurityGroups for ScheduledFargateTask ​

ts
const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 1 });
const cluster = new ecs.Cluster(this, 'EcsCluster', { vpc });
const securityGroup = new ec2.SecurityGroup(this, 'SG', { vpc });

const scheduledFargateTask = new ecsPatterns.ScheduledFargateTask(this, 'ScheduledFargateTask', {
  cluster,
  scheduledFargateTaskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
    memoryLimitMiB: 512,
  },
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  securityGroups: [securityGroup],
});
python
vpc = ec2.Vpc(self, "Vpc", max_azs=1)
cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)
security_group = ec2.SecurityGroup(self, "SG", vpc=vpc)

scheduled_fargate_task = ecs_patterns.ScheduledFargateTask(self, "ScheduledFargateTask",
    cluster=cluster,
    scheduled_fargate_task_image_options=ecsPatterns.ScheduledFargateTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        memory_limit_mi_b=512
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    security_groups=[security_group]
)
java
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();
csharp
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var securityGroup = new SecurityGroup(this, "SG", new SecurityGroupProps { Vpc = vpc });

var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
    Cluster = cluster,
    ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        MemoryLimitMiB = 512
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    SecurityGroups = new [] { securityGroup }
});
go
vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(1),
})
cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	Vpc: Vpc,
})
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SG"), &SecurityGroupProps{
	Vpc: Vpc,
})

scheduledFargateTask := ecsPatterns.NewScheduledFargateTask(this, jsii.String("ScheduledFargateTask"), &ScheduledFargateTaskProps{
	Cluster: Cluster,
	ScheduledFargateTaskImageOptions: &ScheduledFargateTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		MemoryLimitMiB: jsii.Number(512),
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
})

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:

ts
declare const cluster: ecs.Cluster;
declare const vpc: ec2.Vpc;
const service = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  vpc,
  desiredCount: 1,
  minHealthyPercent: 100,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
    dockerLabels: {
      'application.label.one': 'first_label',
      'application.label.two': 'second_label',
    },
  },
});

service.taskDefinition.addContainer('Sidecar', {
  image: ecs.ContainerImage.fromRegistry('example/metrics-sidecar'),
});
python
# cluster: ecs.Cluster
# vpc: ec2.Vpc

service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    vpc=vpc,
    desired_count=1,
    min_healthy_percent=100,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        docker_labels={
            "application.label.one": "first_label",
            "application.label.two": "second_label"
        }
    )
)

service.task_definition.add_container("Sidecar",
    image=ecs.ContainerImage.from_registry("example/metrics-sidecar")
)
java
Cluster cluster;
Vpc vpc;

ApplicationLoadBalancedFargateService service = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .vpc(vpc)
        .desiredCount(1)
        .minHealthyPercent(100)
        .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());
csharp
Cluster cluster;
Vpc vpc;

var service = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    Vpc = vpc,
    DesiredCount = 1,
    MinHealthyPercent = 100,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        DockerLabels = new Dictionary<string, string> {
            { "application.label.one", "first_label" },
            { "application.label.two", "second_label" }
        }
    }
});

service.TaskDefinition.AddContainer("Sidecar", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example/metrics-sidecar")
});
go
var cluster Cluster
var vpc Vpc

service := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	Vpc: Vpc,
	DesiredCount: jsii.Number(1),
	MinHealthyPercent: jsii.Number(100),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		DockerLabels: map[string]*string{
			"application.label.one": jsii.String("first_label"),
			"application.label.two": jsii.String("second_label"),
		},
	},
})

service.TaskDefinition.AddContainer(jsii.String("Sidecar"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_*FromRegistry(jsii.String("example/metrics-sidecar")),
})

Select specific load balancer name ApplicationLoadBalancedFargateService ​

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  taskSubnets: {
    subnets: [ec2.Subnet.fromSubnetId(this, 'subnet', 'VpcISOLATEDSubnet1Subnet80F07FA0')],
  },
  loadBalancerName: 'application-lb-name',
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    task_subnets=ec2.SubnetSelection(
        subnets=[ec2.Subnet.from_subnet_id(self, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")]
    ),
    load_balancer_name="application-lb-name"
)
java
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())
        .minHealthyPercent(100)
        .taskSubnets(SubnetSelection.builder()
                .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                .build())
        .loadBalancerName("application-lb-name")
        .build();
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    TaskSubnets = new SubnetSelection {
        Subnets = new [] { Subnet.FromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0") }
    },
    LoadBalancerName = "application-lb-name"
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	TaskSubnets: &SubnetSelection{
		Subnets: []ISubnet{
			ec2.Subnet_FromSubnetId(this, jsii.String("subnet"), jsii.String("VpcISOLATEDSubnet1Subnet80F07FA0")),
		},
	},
	LoadBalancerName: jsii.String("application-lb-name"),
})

ECS Exec ​

You can use ECS Exec to run commands in or get a shell to a container running on an Amazon EC2 instance or on AWS Fargate. Enable ECS Exec, by setting enableExecuteCommand to true.

ECS Exec is supported by all Services i.e. ApplicationLoadBalanced(Fargate|Ec2)Service, ApplicationMultipleTargetGroups(Fargate|Ec2)Service, NetworkLoadBalanced(Fargate|Ec2)Service, NetworkMultipleTargetGroups(Fargate|Ec2)Service, QueueProcessing(Fargate|Ec2)Service. It is not supported for ScheduledTasks.

Read more about ECS Exec in the ECS Developer Guide.

Example:

ts
declare const cluster: ecs.Cluster;
const loadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  cluster,
  memoryLimitMiB: 1024,
  desiredCount: 1,
  cpu: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  },
  minHealthyPercent: 100,
  enableExecuteCommand: true
});
python
# cluster: ecs.Cluster

load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "Service",
    cluster=cluster,
    memory_limit_mi_b=1024,
    desired_count=1,
    cpu=512,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    enable_execute_command=True
)
java
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())
        .minHealthyPercent(100)
        .enableExecuteCommand(true)
        .build();
csharp
Cluster cluster;

var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    DesiredCount = 1,
    Cpu = 512,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    EnableExecuteCommand = true
});
go
var cluster Cluster

loadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	DesiredCount: jsii.Number(1),
	Cpu: jsii.Number(512),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	EnableExecuteCommand: jsii.Boolean(true),
})

Please note, ECS Exec leverages AWS Systems Manager (SSM). So as a prerequisite for the exec command to work, you need to have the SSM plugin for the AWS CLI installed locally. For more information, see Install Session Manager plugin for AWS CLI.

Propagate Tags from task definition for ScheduledFargateTask ​

For tasks that are defined by a Task Definition, tags applied to the definition will not be applied to the running task by default. To get this behavior, set propagateTags to ecs.PropagatedTagSource.TASK_DEFINITION as shown below:

ts
import { Tags } from 'aws-cdk-lib';

const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 1 });
const cluster = new ecs.Cluster(this, 'EcsCluster', { vpc });
const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
taskDefinition.addContainer("WebContainer", {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
});
Tags.of(taskDefinition).add('my-tag', 'my-tag-value')
const scheduledFargateTask = new ecsPatterns.ScheduledFargateTask(this, 'ScheduledFargateTask', {
  cluster,
  taskDefinition: taskDefinition,
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  propagateTags: ecs.PropagatedTagSource.TASK_DEFINITION,
});
python
from aws_cdk import Tags


vpc = ec2.Vpc(self, "Vpc", max_azs=1)
cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)
task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    memory_limit_mi_b=512,
    cpu=256
)
task_definition.add_container("WebContainer",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
)
Tags.of(task_definition).add("my-tag", "my-tag-value")
scheduled_fargate_task = ecs_patterns.ScheduledFargateTask(self, "ScheduledFargateTask",
    cluster=cluster,
    task_definition=task_definition,
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    propagate_tags=ecs.PropagatedTagSource.TASK_DEFINITION
)
java
import software.amazon.awscdk.Tags;


Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .memoryLimitMiB(512)
        .cpu(256)
        .build();
taskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .build());
Tags.of(taskDefinition).add("my-tag", "my-tag-value");
ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .schedule(Schedule.expression("rate(1 minute)"))
        .propagateTags(PropagatedTagSource.TASK_DEFINITION)
        .build();
csharp
using Amazon.CDK;


var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    MemoryLimitMiB = 512,
    Cpu = 256
});
taskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
});
Tags.Of(taskDefinition).Add("my-tag", "my-tag-value");
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    Schedule = Schedule.Expression("rate(1 minute)"),
    PropagateTags = PropagatedTagSource.TASK_DEFINITION
});
go
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(1),
})
cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	Vpc: Vpc,
})
taskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	MemoryLimitMiB: jsii.Number(512),
	Cpu: jsii.Number(256),
})
taskDefinition.AddContainer(jsii.String("WebContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
})
awscdk.Tags_Of(taskDefinition).Add(jsii.String("my-tag"), jsii.String("my-tag-value"))
scheduledFargateTask := ecsPatterns.NewScheduledFargateTask(this, jsii.String("ScheduledFargateTask"), &ScheduledFargateTaskProps{
	Cluster: Cluster,
	TaskDefinition: taskDefinition,
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	PropagateTags: ecs.PropagatedTagSource_TASK_DEFINITION,
})

Pass a list of tags for ScheduledFargateTask ​

You can pass a list of tags to be applied to a Fargate task directly. These tags are in addition to any tags that could be applied to the task definition and propagated using the propagateTags attribute.

ts
const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 1 });
const cluster = new ecs.Cluster(this, 'EcsCluster', { vpc });
const scheduledFargateTask = new ecsPatterns.ScheduledFargateTask(this, 'ScheduledFargateTask', {
  cluster,
  scheduledFargateTaskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
    memoryLimitMiB: 512,
  },
  schedule: appscaling.Schedule.expression('rate(1 minute)'),
  tags: [
    {
      key: 'my-tag',
      value: 'my-tag-value',
    },
  ],
});
python
from aws_cdk.aws_events_targets import Tag
vpc = ec2.Vpc(self, "Vpc", max_azs=1)
cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)
scheduled_fargate_task = ecs_patterns.ScheduledFargateTask(self, "ScheduledFargateTask",
    cluster=cluster,
    scheduled_fargate_task_image_options=ecsPatterns.ScheduledFargateTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
        memory_limit_mi_b=512
    ),
    schedule=appscaling.Schedule.expression("rate(1 minute)"),
    tags=[Tag(
        key="my-tag",
        value="my-tag-value"
    )
    ]
)
java
Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
Cluster cluster = Cluster.Builder.create(this, "EcsCluster").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)"))
        .tags(List.of(Tag.builder()
                .key("my-tag")
                .value("my-tag-value")
                .build()))
        .build();
csharp
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
    Cluster = cluster,
    ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
        MemoryLimitMiB = 512
    },
    Schedule = Schedule.Expression("rate(1 minute)"),
    Tags = new [] { new Tag {
        Key = "my-tag",
        Value = "my-tag-value"
    } }
});
go
vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(1),
})
cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	Vpc: Vpc,
})
scheduledFargateTask := ecsPatterns.NewScheduledFargateTask(this, jsii.String("ScheduledFargateTask"), &ScheduledFargateTaskProps{
	Cluster: Cluster,
	ScheduledFargateTaskImageOptions: &ScheduledFargateTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
		MemoryLimitMiB: jsii.Number(512),
	},
	Schedule: appscaling.Schedule_Expression(jsii.String("rate(1 minute)")),
	Tags: []Tag{
		&Tag{
			Key: jsii.String("my-tag"),
			Value: jsii.String("my-tag-value"),
		},
	},
})

Use custom ephemeral storage for ECS Fargate tasks ​

You can pass a custom ephemeral storage (21GiB - 200GiB) to ECS Fargate tasks on Fargate Platform Version 1.4.0 or later.

ts
const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 2, restrictDefaultSecurityGroup: false });
const cluster = new ecs.Cluster(this, 'FargateCluster', { vpc });

const applicationLoadBalancedFargateService = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'ALBFargateServiceWithCustomEphemeralStorage', {
  cluster,
  memoryLimitMiB: 1024,
  cpu: 512,
  ephemeralStorageGiB: 21,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
});

const networkLoadBalancedFargateService = new ecsPatterns.NetworkLoadBalancedFargateService(this, 'NLBFargateServiceWithCustomEphemeralStorage', {
  cluster,
  memoryLimitMiB: 1024,
  cpu: 512,
  ephemeralStorageGiB: 200,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
});
python
vpc = ec2.Vpc(self, "Vpc", max_azs=2, restrict_default_security_group=False)
cluster = ecs.Cluster(self, "FargateCluster", vpc=vpc)

application_load_balanced_fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "ALBFargateServiceWithCustomEphemeralStorage",
    cluster=cluster,
    memory_limit_mi_b=1024,
    cpu=512,
    ephemeral_storage_gi_b=21,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100
)

network_load_balanced_fargate_service = ecs_patterns.NetworkLoadBalancedFargateService(self, "NLBFargateServiceWithCustomEphemeralStorage",
    cluster=cluster,
    memory_limit_mi_b=1024,
    cpu=512,
    ephemeral_storage_gi_b=200,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100
)
java
Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(2).restrictDefaultSecurityGroup(false).build();
Cluster cluster = Cluster.Builder.create(this, "FargateCluster").vpc(vpc).build();

ApplicationLoadBalancedFargateService applicationLoadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "ALBFargateServiceWithCustomEphemeralStorage")
        .cluster(cluster)
        .memoryLimitMiB(1024)
        .cpu(512)
        .ephemeralStorageGiB(21)
        .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .build();

NetworkLoadBalancedFargateService networkLoadBalancedFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "NLBFargateServiceWithCustomEphemeralStorage")
        .cluster(cluster)
        .memoryLimitMiB(1024)
        .cpu(512)
        .ephemeralStorageGiB(200)
        .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .build();
csharp
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 2, RestrictDefaultSecurityGroup = false });
var cluster = new Cluster(this, "FargateCluster", new ClusterProps { Vpc = vpc });

var applicationLoadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "ALBFargateServiceWithCustomEphemeralStorage", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    Cpu = 512,
    EphemeralStorageGiB = 21,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100
});

var networkLoadBalancedFargateService = new NetworkLoadBalancedFargateService(this, "NLBFargateServiceWithCustomEphemeralStorage", new NetworkLoadBalancedFargateServiceProps {
    Cluster = cluster,
    MemoryLimitMiB = 1024,
    Cpu = 512,
    EphemeralStorageGiB = 200,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100
});
go
vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	MaxAzs: jsii.Number(2),
	RestrictDefaultSecurityGroup: jsii.Boolean(false),
})
cluster := ecs.NewCluster(this, jsii.String("FargateCluster"), &ClusterProps{
	Vpc: Vpc,
})

applicationLoadBalancedFargateService := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("ALBFargateServiceWithCustomEphemeralStorage"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	Cpu: jsii.Number(512),
	EphemeralStorageGiB: jsii.Number(21),
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
})

networkLoadBalancedFargateService := ecsPatterns.NewNetworkLoadBalancedFargateService(this, jsii.String("NLBFargateServiceWithCustomEphemeralStorage"), &NetworkLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	MemoryLimitMiB: jsii.Number(1024),
	Cpu: jsii.Number(512),
	EphemeralStorageGiB: jsii.Number(200),
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_*FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
})

Set healthCheckGracePeriod for QueueProcessingFargateService ​

ts
declare const vpc: ec2.Vpc;
const queueProcessingFargateService = new ecsPatterns.QueueProcessingFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  image: ecs.ContainerImage.fromRegistry('test'),
  minHealthyPercent: 100,
  healthCheckGracePeriod: Duration.seconds(120),
});
python
# vpc: ec2.Vpc

queue_processing_fargate_service = ecs_patterns.QueueProcessingFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    image=ecs.ContainerImage.from_registry("test"),
    min_healthy_percent=100,
    health_check_grace_period=Duration.seconds(120)
)
java
Vpc vpc;

QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
        .vpc(vpc)
        .memoryLimitMiB(512)
        .image(ContainerImage.fromRegistry("test"))
        .minHealthyPercent(100)
        .healthCheckGracePeriod(Duration.seconds(120))
        .build();
csharp
Vpc vpc;

var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    Image = ContainerImage.FromRegistry("test"),
    MinHealthyPercent = 100,
    HealthCheckGracePeriod = Duration.Seconds(120)
});
go
var vpc Vpc

queueProcessingFargateService := ecsPatterns.NewQueueProcessingFargateService(this, jsii.String("Service"), &QueueProcessingFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MinHealthyPercent: jsii.Number(100),
	HealthCheckGracePeriod: awscdk.Duration_Seconds(jsii.Number(120)),
})

Set securityGroups for NetworkLoadBalancedFargateService ​

ts
declare const vpc: ec2.Vpc;
declare const securityGroup: ec2.SecurityGroup;
const queueProcessingFargateService = new ecsPatterns.NetworkLoadBalancedFargateService(this, 'Service', {
  vpc,
  memoryLimitMiB: 512,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
  securityGroups: [securityGroup],
});
python
# vpc: ec2.Vpc
# security_group: ec2.SecurityGroup

queue_processing_fargate_service = ecs_patterns.NetworkLoadBalancedFargateService(self, "Service",
    vpc=vpc,
    memory_limit_mi_b=512,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    security_groups=[security_group]
)
java
Vpc vpc;
SecurityGroup securityGroup;

NetworkLoadBalancedFargateService queueProcessingFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "Service")
        .vpc(vpc)
        .memoryLimitMiB(512)
        .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .securityGroups(List.of(securityGroup))
        .build();
csharp
Vpc vpc;
SecurityGroup securityGroup;

var queueProcessingFargateService = new NetworkLoadBalancedFargateService(this, "Service", new NetworkLoadBalancedFargateServiceProps {
    Vpc = vpc,
    MemoryLimitMiB = 512,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    SecurityGroups = new [] { securityGroup }
});
go
var vpc Vpc
var securityGroup SecurityGroup

queueProcessingFargateService := ecsPatterns.NewNetworkLoadBalancedFargateService(this, jsii.String("Service"), &NetworkLoadBalancedFargateServiceProps{
	Vpc: Vpc,
	MemoryLimitMiB: jsii.Number(512),
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
})

Set TLS for NetworkLoadBalancedFargateService / NetworkLoadBalancedEc2Service ​

To set up TLS listener in Network Load Balancer, you need to pass extactly one ACM certificate into the option listenerCertificate. The listener port and the target group port will also become 443 by default. You can override the listener's port with listenerPort and the target group's port with taskImageOptions.containerPort.

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

const certificate = Certificate.fromCertificateArn(this, 'Cert', 'arn:aws:acm:us-east-1:123456:certificate/abcdefg');
const loadBalancedFargateService = new ecsPatterns.NetworkLoadBalancedFargateService(this, 'Service', {
  // 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('amazon/amazon-ecs-sample'),
    // The default value of containerPort is 443 if you pass in listenerCertificate
    // It is configured to port 8443 here
    containerPort: 8443,
  },
});
python
from aws_cdk.aws_certificatemanager import Certificate


certificate = Certificate.from_certificate_arn(self, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg")
load_balanced_fargate_service = ecs_patterns.NetworkLoadBalancedFargateService(self, "Service",
    # 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("amazon/amazon-ecs-sample"),
        # The default value of containerPort is 443 if you pass in listenerCertificate
        # It is configured to port 8443 here
        container_port=8443
    )
)
java
import software.amazon.awscdk.services.certificatemanager.Certificate;


ICertificate certificate = Certificate.fromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
NetworkLoadBalancedFargateService loadBalancedFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "Service")
        // 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("amazon/amazon-ecs-sample"))
                // The default value of containerPort is 443 if you pass in listenerCertificate
                // It is configured to port 8443 here
                .containerPort(8443)
                .build())
        .build();
csharp
using Amazon.CDK.AWS.CertificateManager;


var certificate = Certificate.FromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
var loadBalancedFargateService = new NetworkLoadBalancedFargateService(this, "Service", new NetworkLoadBalancedFargateServiceProps {
    // 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("amazon/amazon-ecs-sample"),
        // The default value of containerPort is 443 if you pass in listenerCertificate
        // It is configured to port 8443 here
        ContainerPort = 8443
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


certificate := awscdk.Certificate_FromCertificateArn(this, jsii.String("Cert"), jsii.String("arn:aws:acm:us-east-1:123456:certificate/abcdefg"))
loadBalancedFargateService := ecsPatterns.NewNetworkLoadBalancedFargateService(this, jsii.String("Service"), &NetworkLoadBalancedFargateServiceProps{
	// 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("amazon/amazon-ecs-sample")),
		// The default value of containerPort is 443 if you pass in listenerCertificate
		// It is configured to port 8443 here
		ContainerPort: jsii.Number(8443),
	},
})
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
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
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),
})

Use dualstack Load Balancer ​

You can use dualstack IP address type for Application Load Balancer and Network Load Balancer.

To use dualstack IP address type, you must have associated IPv6 CIDR blocks with the VPC and subnets and set the ipAddressType to IpAddressType.DUAL_STACK when creating the load balancer.

Application Load Balancer ​

You can use dualstack Application Load Balancer for Fargate and EC2 services.

ts
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';

// The VPC and subnet must have associated IPv6 CIDR blocks.
const vpc = new ec2.Vpc(this, 'Vpc', {
  ipProtocol: ec2.IpProtocol.DUAL_STACK,
});
const cluster = new ecs.Cluster(this, 'EcsCluster', { vpc });

const service = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'myService', {
  cluster,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
});

const applicationLoadBalancedEc2Service = new ecsPatterns.ApplicationLoadBalancedEc2Service(this, 'myService', {
  cluster,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
});
python
import aws_cdk.aws_elasticloadbalancingv2 as elbv2


# The VPC and subnet must have associated IPv6 CIDR blocks.
vpc = ec2.Vpc(self, "Vpc",
    ip_protocol=ec2.IpProtocol.DUAL_STACK
)
cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)

service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "myService",
    cluster=cluster,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK
)

application_load_balanced_ec2_service = ecs_patterns.ApplicationLoadBalancedEc2Service(self, "myService",
    cluster=cluster,
    task_image_options=ecsPatterns.ApplicationLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK
)
java
import software.amazon.awscdk.services.elasticloadbalancingv2.*;


// The VPC and subnet must have associated IPv6 CIDR blocks.
Vpc vpc = Vpc.Builder.create(this, "Vpc")
        .ipProtocol(IpProtocol.DUAL_STACK)
        .build();
Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();

ApplicationLoadBalancedFargateService service = ApplicationLoadBalancedFargateService.Builder.create(this, "myService")
        .cluster(cluster)
        .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();

ApplicationLoadBalancedEc2Service applicationLoadBalancedEc2Service = ApplicationLoadBalancedEc2Service.Builder.create(this, "myService")
        .cluster(cluster)
        .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
using Amazon.CDK.AWS.ElasticLoadBalancingV2;


// The VPC and subnet must have associated IPv6 CIDR blocks.
var vpc = new Vpc(this, "Vpc", new VpcProps {
    IpProtocol = IpProtocol.DUAL_STACK
});
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });

var service = new ApplicationLoadBalancedFargateService(this, "myService", new ApplicationLoadBalancedFargateServiceProps {
    Cluster = cluster,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    IpAddressType = IpAddressType.DUAL_STACK
});

var applicationLoadBalancedEc2Service = new ApplicationLoadBalancedEc2Service(this, "myService", new ApplicationLoadBalancedEc2ServiceProps {
    Cluster = cluster,
    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    IpAddressType = IpAddressType.DUAL_STACK
});
go
import "github.com/aws/aws-cdk-go/awscdk"


// The VPC and subnet must have associated IPv6 CIDR blocks.
vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	IpProtocol: ec2.IpProtocol_DUAL_STACK,
})
cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	Vpc: Vpc,
})

service := ecsPatterns.NewApplicationLoadBalancedFargateService(this, jsii.String("myService"), &ApplicationLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
})

applicationLoadBalancedEc2Service := ecsPatterns.NewApplicationLoadBalancedEc2Service(this, jsii.String("myService"), &ApplicationLoadBalancedEc2ServiceProps{
	Cluster: Cluster,
	TaskImageOptions: &ApplicationLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_*FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
})

Network Load Balancer ​

You can use dualstack Network Load Balancer for Fargate and EC2 services.

ts
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';

// The VPC and subnet must have associated IPv6 CIDR blocks.
const vpc = new ec2.Vpc(this, 'Vpc', {
  ipProtocol: ec2.IpProtocol.DUAL_STACK,
});
const cluster = new ecs.Cluster(this, 'EcsCluster', { vpc });

const networkLoadbalancedFargateService = new ecsPatterns.NetworkLoadBalancedFargateService(this, 'NlbFargateService', {
  cluster,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
});

const networkLoadbalancedEc2Service = new ecsPatterns.NetworkLoadBalancedEc2Service(this, 'NlbEc2Service', {
  cluster,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  },
  minHealthyPercent: 100,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
});
python
import aws_cdk.aws_elasticloadbalancingv2 as elbv2


# The VPC and subnet must have associated IPv6 CIDR blocks.
vpc = ec2.Vpc(self, "Vpc",
    ip_protocol=ec2.IpProtocol.DUAL_STACK
)
cluster = ecs.Cluster(self, "EcsCluster", vpc=vpc)

network_loadbalanced_fargate_service = ecs_patterns.NetworkLoadBalancedFargateService(self, "NlbFargateService",
    cluster=cluster,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK
)

network_loadbalanced_ec2_service = ecs_patterns.NetworkLoadBalancedEc2Service(self, "NlbEc2Service",
    cluster=cluster,
    task_image_options=ecsPatterns.NetworkLoadBalancedTaskImageOptions(
        image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
    ),
    min_healthy_percent=100,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK
)
java
import software.amazon.awscdk.services.elasticloadbalancingv2.*;


// The VPC and subnet must have associated IPv6 CIDR blocks.
Vpc vpc = Vpc.Builder.create(this, "Vpc")
        .ipProtocol(IpProtocol.DUAL_STACK)
        .build();
Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();

NetworkLoadBalancedFargateService networkLoadbalancedFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "NlbFargateService")
        .cluster(cluster)
        .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();

NetworkLoadBalancedEc2Service networkLoadbalancedEc2Service = NetworkLoadBalancedEc2Service.Builder.create(this, "NlbEc2Service")
        .cluster(cluster)
        .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                .build())
        .minHealthyPercent(100)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
using Amazon.CDK.AWS.ElasticLoadBalancingV2;


// The VPC and subnet must have associated IPv6 CIDR blocks.
var vpc = new Vpc(this, "Vpc", new VpcProps {
    IpProtocol = IpProtocol.DUAL_STACK
});
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });

var networkLoadbalancedFargateService = new NetworkLoadBalancedFargateService(this, "NlbFargateService", new NetworkLoadBalancedFargateServiceProps {
    Cluster = cluster,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    IpAddressType = IpAddressType.DUAL_STACK
});

var networkLoadbalancedEc2Service = new NetworkLoadBalancedEc2Service(this, "NlbEc2Service", new NetworkLoadBalancedEc2ServiceProps {
    Cluster = cluster,
    TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
        Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
    },
    MinHealthyPercent = 100,
    IpAddressType = IpAddressType.DUAL_STACK
});
go
import "github.com/aws/aws-cdk-go/awscdk"


// The VPC and subnet must have associated IPv6 CIDR blocks.
vpc := ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
	IpProtocol: ec2.IpProtocol_DUAL_STACK,
})
cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	Vpc: Vpc,
})

networkLoadbalancedFargateService := ecsPatterns.NewNetworkLoadBalancedFargateService(this, jsii.String("NlbFargateService"), &NetworkLoadBalancedFargateServiceProps{
	Cluster: Cluster,
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
})

networkLoadbalancedEc2Service := ecsPatterns.NewNetworkLoadBalancedEc2Service(this, jsii.String("NlbEc2Service"), &NetworkLoadBalancedEc2ServiceProps{
	Cluster: Cluster,
	TaskImageOptions: &NetworkLoadBalancedTaskImageOptions{
		Image: ecs.ContainerImage_*FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	},
	MinHealthyPercent: jsii.Number(100),
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
})

Types ​

NameKindSummary
ApplicationLoadBalancedEc2ServiceConstruct (L3)An EC2 service running on an ECS cluster fronted by an application load balancer.
ApplicationLoadBalancedFargateServiceConstruct (L3)A Fargate service running on an ECS cluster fronted by an application load balancer.
ApplicationLoadBalancedServiceBaseConstruct (L3)The base class for ApplicationLoadBalancedEc2Service and ApplicationLoadBalancedFargateService services.
ApplicationMultipleTargetGroupsEc2ServiceConstruct (L3)An EC2 service running on an ECS cluster fronted by an application load balancer.
ApplicationMultipleTargetGroupsFargateServiceConstruct (L3)A Fargate service running on an ECS cluster fronted by an application load balancer.
ApplicationMultipleTargetGroupsServiceBaseConstruct (L3)The base class for ApplicationMultipleTargetGroupsEc2Service and ApplicationMultipleTargetGroupsFargateService classes.
NetworkLoadBalancedEc2ServiceConstruct (L3)An EC2 service running on an ECS cluster fronted by a network load balancer.
NetworkLoadBalancedFargateServiceConstruct (L3)A Fargate service running on an ECS cluster fronted by a network load balancer.
NetworkLoadBalancedServiceBaseConstruct (L3)The base class for NetworkLoadBalancedEc2Service and NetworkLoadBalancedFargateService services.
NetworkMultipleTargetGroupsEc2ServiceConstruct (L3)An EC2 service running on an ECS cluster fronted by a network load balancer.
NetworkMultipleTargetGroupsFargateServiceConstruct (L3)A Fargate service running on an ECS cluster fronted by a network load balancer.
NetworkMultipleTargetGroupsServiceBaseConstruct (L3)The base class for NetworkMultipleTargetGroupsEc2Service and NetworkMultipleTargetGroupsFargateService classes.
QueueProcessingEc2ServiceConstruct (L3)Class to create a queue processing EC2 service.
QueueProcessingFargateServiceConstruct (L3)Class to create a queue processing Fargate service.
QueueProcessingServiceBaseConstruct (L3)The base class for QueueProcessingEc2Service and QueueProcessingFargateService services.
ScheduledEc2TaskConstruct (L3)A scheduled EC2 task that will be initiated off of CloudWatch Events.
ScheduledFargateTaskConstruct (L3)A scheduled Fargate task that will be initiated off of CloudWatch Events.
ScheduledTaskBaseConstruct (L3)The base class for ScheduledEc2Task and ScheduledFargateTask tasks.
ApplicationListenerPropsStructProperties to define an application listener.
ApplicationLoadBalancedEc2ServicePropsStructThe properties for the ApplicationLoadBalancedEc2Service service.
ApplicationLoadBalancedFargateServicePropsStructThe properties for the ApplicationLoadBalancedFargateService service.
ApplicationLoadBalancedServiceBasePropsStructThe properties for the base ApplicationLoadBalancedEc2Service or ApplicationLoadBalancedFargateService service.
ApplicationLoadBalancedServiceRecordTypeEnumDescribes the type of DNS record the service should create.
ApplicationLoadBalancedTaskImageOptionsStruct
ApplicationLoadBalancedTaskImagePropsStructOptions for configuring a new container.
ApplicationLoadBalancerPropsStructProperties to define an application load balancer.
ApplicationMultipleTargetGroupsEc2ServicePropsStructThe properties for the ApplicationMultipleTargetGroupsEc2Service service.
ApplicationMultipleTargetGroupsFargateServicePropsStructThe properties for the ApplicationMultipleTargetGroupsFargateService service.
ApplicationMultipleTargetGroupsServiceBasePropsStructThe properties for the base ApplicationMultipleTargetGroupsEc2Service or ApplicationMultipleTargetGroupsFargateService service.
ApplicationTargetPropsStructProperties to define an application target group.
FargateServiceBasePropsStruct
NetworkListenerPropsStructProperties to define an network listener.
NetworkLoadBalancedEc2ServicePropsStructThe properties for the NetworkLoadBalancedEc2Service service.
NetworkLoadBalancedFargateServicePropsStructThe properties for the NetworkLoadBalancedFargateService service.
NetworkLoadBalancedServiceBasePropsStructThe properties for the base NetworkLoadBalancedEc2Service or NetworkLoadBalancedFargateService service.
NetworkLoadBalancedServiceRecordTypeEnumDescribes the type of DNS record the service should create.
NetworkLoadBalancedTaskImageOptionsStruct
NetworkLoadBalancedTaskImagePropsStructOptions for configuring a new container.
NetworkLoadBalancerPropsStructProperties to define an network load balancer.
NetworkMultipleTargetGroupsEc2ServicePropsStructThe properties for the NetworkMultipleTargetGroupsEc2Service service.
NetworkMultipleTargetGroupsFargateServicePropsStructThe properties for the NetworkMultipleTargetGroupsFargateService service.
NetworkMultipleTargetGroupsServiceBasePropsStructThe properties for the base NetworkMultipleTargetGroupsEc2Service or NetworkMultipleTargetGroupsFargateService service.
NetworkTargetPropsStructProperties to define a network load balancer target group.
QueueProcessingEc2ServicePropsStructThe properties for the QueueProcessingEc2Service service.
QueueProcessingFargateServicePropsStructThe properties for the QueueProcessingFargateService service.
QueueProcessingServiceBasePropsStructThe properties for the base QueueProcessingEc2Service or QueueProcessingFargateService service.
ScheduledEc2TaskDefinitionOptionsStructThe properties for the ScheduledEc2Task using a task definition.
ScheduledEc2TaskImageOptionsStructThe properties for the ScheduledEc2Task using an image.
ScheduledEc2TaskPropsStructThe properties for the ScheduledEc2Task task.
ScheduledFargateTaskDefinitionOptionsStructThe properties for the ScheduledFargateTask using a task definition.
ScheduledFargateTaskImageOptionsStructThe properties for the ScheduledFargateTask using an image.
ScheduledFargateTaskPropsStructThe properties for the ScheduledFargateTask task.
ScheduledTaskBasePropsStructThe properties for the base ScheduledEc2Task or ScheduledFargateTask task.
ScheduledTaskImagePropsStruct