@Stability(value=Stable)
See: Description
Interface | Description |
---|---|
AddAutoScalingGroupCapacityOptions |
The properties for adding an AutoScalingGroup.
|
AddCapacityOptions |
The properties for adding instance capacity to an AutoScalingGroup.
|
AppMeshProxyConfigurationConfigProps |
The configuration to use when setting an App Mesh proxy configuration.
|
AppMeshProxyConfigurationProps |
Interface for setting the properties of proxy configuration.
|
AssetImageProps |
The properties for building an AssetImage.
|
AuthorizationConfig |
The authorization configuration details for the Amazon EFS file system.
|
AwsLogDriverProps |
Specifies the awslogs log driver configuration options.
|
BaseLogDriverProps | |
BaseServiceOptions |
The properties for the base Ec2Service or FargateService service.
|
BaseServiceProps |
Complete base service properties that are required to be supplied by the implementation of the BaseService class.
|
BottleRocketImageProps |
Properties for BottleRocketImage.
|
CapacityProviderStrategy |
A Capacity Provider strategy to use for the service.
|
CfnCapacityProvider.AutoScalingGroupProviderProperty | |
CfnCapacityProvider.ManagedScalingProperty | |
CfnCapacityProviderProps |
Properties for defining a `AWS::ECS::CapacityProvider`.
|
CfnCluster.CapacityProviderStrategyItemProperty | |
CfnCluster.ClusterConfigurationProperty | |
CfnCluster.ClusterSettingsProperty | |
CfnCluster.ExecuteCommandConfigurationProperty | |
CfnCluster.ExecuteCommandLogConfigurationProperty | |
CfnClusterProps |
Properties for defining a `AWS::ECS::Cluster`.
|
CfnPrimaryTaskSetProps |
Properties for defining a `AWS::ECS::PrimaryTaskSet`.
|
CfnService.AwsVpcConfigurationProperty | |
CfnService.CapacityProviderStrategyItemProperty | |
CfnService.DeploymentCircuitBreakerProperty | |
CfnService.DeploymentConfigurationProperty | |
CfnService.DeploymentControllerProperty | |
CfnService.LoadBalancerProperty | |
CfnService.NetworkConfigurationProperty | |
CfnService.PlacementConstraintProperty | |
CfnService.PlacementStrategyProperty | |
CfnService.ServiceRegistryProperty | |
CfnServiceProps |
Properties for defining a `AWS::ECS::Service`.
|
CfnTaskDefinition.AuthorizationConfigProperty | |
CfnTaskDefinition.ContainerDefinitionProperty | |
CfnTaskDefinition.ContainerDependencyProperty | |
CfnTaskDefinition.DeviceProperty | |
CfnTaskDefinition.DockerVolumeConfigurationProperty | |
CfnTaskDefinition.EfsVolumeConfigurationProperty | |
CfnTaskDefinition.EnvironmentFileProperty | |
CfnTaskDefinition.FirelensConfigurationProperty | |
CfnTaskDefinition.HealthCheckProperty | |
CfnTaskDefinition.HostEntryProperty | |
CfnTaskDefinition.HostVolumePropertiesProperty | |
CfnTaskDefinition.InferenceAcceleratorProperty | |
CfnTaskDefinition.KernelCapabilitiesProperty | |
CfnTaskDefinition.KeyValuePairProperty | |
CfnTaskDefinition.LinuxParametersProperty | |
CfnTaskDefinition.LogConfigurationProperty | |
CfnTaskDefinition.MountPointProperty | |
CfnTaskDefinition.PortMappingProperty | |
CfnTaskDefinition.ProxyConfigurationProperty | |
CfnTaskDefinition.RepositoryCredentialsProperty | |
CfnTaskDefinition.ResourceRequirementProperty | |
CfnTaskDefinition.SecretProperty | |
CfnTaskDefinition.SystemControlProperty | |
CfnTaskDefinition.TaskDefinitionPlacementConstraintProperty | |
CfnTaskDefinition.TmpfsProperty | |
CfnTaskDefinition.UlimitProperty | |
CfnTaskDefinition.VolumeFromProperty | |
CfnTaskDefinition.VolumeProperty | |
CfnTaskDefinitionProps |
Properties for defining a `AWS::ECS::TaskDefinition`.
|
CfnTaskSet.AwsVpcConfigurationProperty | |
CfnTaskSet.LoadBalancerProperty | |
CfnTaskSet.NetworkConfigurationProperty | |
CfnTaskSet.ScaleProperty | |
CfnTaskSet.ServiceRegistryProperty | |
CfnTaskSetProps |
Properties for defining a `AWS::ECS::TaskSet`.
|
CloudMapNamespaceOptions |
The options for creating an AWS Cloud Map namespace.
|
CloudMapOptions |
The options to enabling AWS Cloud Map for an Amazon ECS service.
|
ClusterAttributes |
The properties to import from the ECS cluster.
|
ClusterProps |
The properties used to define an ECS cluster.
|
CommonTaskDefinitionProps |
The common properties for all task definitions.
|
ContainerDefinitionOptions | |
ContainerDefinitionProps |
The properties in a container definition.
|
ContainerDependency |
The details of a dependency on another container in the task definition.
|
ContainerImageConfig |
The configuration for creating a container image.
|
CpuUtilizationScalingProps |
The properties for enabling scaling based on CPU utilization.
|
DeploymentCircuitBreaker |
The deployment circuit breaker to use for the service.
|
DeploymentController |
The deployment controller to use for the service.
|
Device |
A container instance host device.
|
DockerVolumeConfiguration |
The configuration for a Docker volume.
|
Ec2ServiceAttributes |
The properties to import from the service using the EC2 launch type.
|
Ec2ServiceProps |
The properties for defining a service using the EC2 launch type.
|
Ec2TaskDefinitionProps |
The properties for a task definition run on an EC2 cluster.
|
EcsOptimizedAmiProps | Deprecated |
EcsTarget | |
EfsVolumeConfiguration |
The configuration for an Elastic FileSystem volume.
|
EnvironmentFileConfig |
Configuration for the environment file.
|
FargateServiceAttributes |
The properties to import from the service using the Fargate launch type.
|
FargateServiceProps |
The properties for defining a service using the Fargate launch type.
|
FargateTaskDefinitionProps |
The properties for a task definition.
|
FirelensConfig |
Firelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef.
|
FireLensLogDriverProps |
Specifies the firelens log driver configuration options.
|
FirelensLogRouterDefinitionOptions |
The options for creating a firelens log router.
|
FirelensLogRouterProps |
The properties in a firelens log router.
|
FirelensOptions |
The options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef-customconfig.
|
FluentdLogDriverProps |
Specifies the fluentd log driver configuration options.
|
GelfLogDriverProps |
Specifies the journald log driver configuration options.
|
HealthCheck |
The health check command and associated configuration parameters for the container.
|
Host |
The details on a container instance bind mount host volume.
|
IBaseService |
The interface for BaseService.
|
IBaseService.Jsii$Default |
Internal default implementation for
IBaseService . |
ICluster |
A regional grouping of one or more container instances on which you can run tasks and services.
|
ICluster.Jsii$Default |
Internal default implementation for
ICluster . |
IEc2Service |
The interface for a service using the EC2 launch type on an ECS cluster.
|
IEc2Service.Jsii$Default |
Internal default implementation for
IEc2Service . |
IEc2TaskDefinition |
The interface of a task definition run on an EC2 cluster.
|
IEc2TaskDefinition.Jsii$Default |
Internal default implementation for
IEc2TaskDefinition . |
IEcsLoadBalancerTarget |
Interface for ECS load balancer target.
|
IEcsLoadBalancerTarget.Jsii$Default |
Internal default implementation for
IEcsLoadBalancerTarget . |
IFargateService |
The interface for a service using the Fargate launch type on an ECS cluster.
|
IFargateService.Jsii$Default |
Internal default implementation for
IFargateService . |
IFargateTaskDefinition |
The interface of a task definition run on a Fargate cluster.
|
IFargateTaskDefinition.Jsii$Default |
Internal default implementation for
IFargateTaskDefinition . |
IService |
The interface for a service.
|
IService.Jsii$Default |
Internal default implementation for
IService . |
ITaskDefinition |
The interface for all task definitions.
|
ITaskDefinition.Jsii$Default |
Internal default implementation for
ITaskDefinition . |
ITaskDefinitionExtension |
An extension for Task Definitions.
|
ITaskDefinitionExtension.Jsii$Default |
Internal default implementation for
ITaskDefinitionExtension . |
JournaldLogDriverProps |
Specifies the journald log driver configuration options.
|
JsonFileLogDriverProps |
Specifies the json-file log driver configuration options.
|
LinuxParametersProps |
The properties for defining Linux-specific options that are applied to the container.
|
LoadBalancerTargetOptions |
Properties for defining an ECS target.
|
LogDriverConfig |
The configuration to use when creating a log driver.
|
MemoryUtilizationScalingProps |
The properties for enabling scaling based on memory utilization.
|
MountPoint |
The details of data volume mount points for a container.
|
PortMapping |
Port mappings allow containers to access ports on the host container instance to send or receive traffic.
|
RepositoryImageProps |
The properties for an image hosted in a public or private repository.
|
RequestCountScalingProps |
The properties for enabling scaling based on Application Load Balancer (ALB) request counts.
|
ScalableTaskCountProps |
The properties of a scalable attribute representing task count.
|
ScratchSpace |
The temporary disk space mounted to the container.
|
SplunkLogDriverProps |
Specifies the splunk log driver configuration options.
|
SyslogLogDriverProps |
Specifies the syslog log driver configuration options.
|
TaskDefinitionProps |
The properties for task definitions.
|
Tmpfs |
The details of a tmpfs mount for a container.
|
TrackCustomMetricProps |
The properties for enabling target tracking scaling based on a custom CloudWatch metric.
|
Ulimit |
The ulimit settings to pass to the container.
|
Volume |
A data volume used in a task definition.
|
VolumeFrom |
The details on a data volume from another container in the same task definition.
|
Enum | Description |
---|---|
AmiHardwareType |
The ECS-optimized AMI variant to use.
|
BinPackResource |
Instance resource used for bin packing.
|
BottlerocketEcsVariant |
Amazon ECS variant.
|
Capability |
A Linux capability.
|
Compatibility |
The task launch type compatibility requirement.
|
ContainerDependencyCondition | |
DeploymentControllerType |
The deployment controller type to use for the service.
|
DevicePermission |
Permissions for device access.
|
EnvironmentFileType |
Type of environment file to be included in the container definition.
|
FargatePlatformVersion |
The platform version on which to run your service.
|
FirelensConfigFileType |
Firelens configuration file type, s3 or file path.
|
FirelensLogRouterType |
Firelens log router type, fluentbit or fluentd.
|
GelfCompressionType |
The type of compression the GELF driver uses to compress each log message.
|
IpcMode |
The IPC resource namespace to use for the containers in the task.
|
LaunchType |
The launch type of an ECS service.
|
MachineImageType |
The machine image type.
|
NetworkMode |
The networking mode to use for the containers in the task.
|
PidMode |
The process namespace to use for the containers in the task.
|
PropagatedTagSource |
Propagate tags from either service or task definition.
|
Protocol |
Network protocol.
|
Scope |
The scope for the Docker volume that determines its lifecycle.
|
SplunkLogFormat |
Log Message Format.
|
TmpfsMountOption |
The supported options for a tmpfs mount for a container.
|
UlimitName |
Type of resource to set a limit on.
|
WindowsOptimizedVersion |
ECS-optimized Windows version list.
|
---
This package contains constructs for working with Amazon Elastic Container Service (Amazon ECS).
Amazon ECS is a highly scalable, fast, container management service that makes it easy to run, stop, and manage Docker containers on a cluster of Amazon EC2 instances.
For further information on Amazon ECS, see the Amazon ECS documentation
The following example creates an Amazon ECS cluster, adds capacity to it, and instantiates the Amazon ECS Service with an automatic load balancer.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.ecs.*; // Create an ECS cluster Cluster cluster = new Cluster(this, "Cluster", new ClusterProps() .vpc(vpc)); // Add capacity to it cluster.addCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions() .instanceType(new InstanceType("t2.xlarge")) .desiredCapacity(3)); Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("DefaultContainer", new ContainerDefinitionOptions() .image(ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample")) .memoryLimitMiB(512)); // Instantiate an Amazon ECS Service Ec2Service ecsService = new Ec2Service(this, "Service", new Ec2ServiceProps() .cluster(cluster) .taskDefinition(taskDefinition));
For a set of constructs defining common ECS architectural patterns, see the @aws-cdk/aws-ecs-patterns
package.
There are two sets of constructs in this library; one to run tasks on Amazon EC2 and one to run tasks on AWS Fargate.
Ec2TaskDefinition
and Ec2Service
constructs to run tasks on Amazon EC2 instances running in your account.FargateTaskDefinition
and FargateService
constructs to run tasks on
instances that are managed for you by AWS.Here are the main differences:
For more information on Amazon EC2 vs AWS Fargate and networking see the AWS Documentation: AWS Fargate and Task Networking.
A Cluster
defines the infrastructure to run your
tasks on. You can run many tasks on a single cluster.
The following code creates a cluster that can run AWS Fargate tasks:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object cluster = Cluster.Builder.create(this, "Cluster") .vpc(vpc) .build();
To use tasks with Amazon EC2 launch-type, you have to add capacity to the cluster in order for tasks to be scheduled on your instances. Typically, you add an AutoScalingGroup with instances running the latest Amazon ECS-optimized AMI to the cluster. There is a method to build and add such an AutoScalingGroup automatically, or you can supply a customized AutoScalingGroup that you construct yourself. It's possible to add multiple AutoScalingGroups with various instance types.
The following example creates an Amazon ECS cluster and adds capacity to it:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object cluster = Cluster.Builder.create(this, "Cluster") .vpc(vpc) .build(); // Either add default capacity cluster.addCapacity("DefaultAutoScalingGroupCapacity", Map.of( "instanceType", new InstanceType("t2.xlarge"), "desiredCapacity", 3)); // Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI. Object autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG") .vpc(vpc) .instanceType(new InstanceType("t2.xlarge")) .machineImage(EcsOptimizedImage.amazonLinux()) // Or use Amazon ECS-Optimized Amazon Linux 2 AMI // machineImage: EcsOptimizedImage.amazonLinux2(), .desiredCapacity(3) .build(); cluster.addAutoScalingGroup(autoScalingGroup);
If you omit the property vpc
, the construct will create a new VPC with two AZs.
Bottlerocket is a Linux-based open source operating system that is purpose-built by AWS for running containers. You can launch Amazon ECS container instances with the Bottlerocket AMI.
NOTICE: The Bottlerocket AMI is in developer preview release for Amazon ECS and is subject to change.
The following example will create a capacity with self-managed Amazon EC2 capacity of 2 c5.large
Linux instances running with Bottlerocket
AMI.
Note that you must specify either a machineImage
or machineImageType
, at least one, not both.
The following example adds Bottlerocket capacity to the cluster:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 cluster.addCapacity("bottlerocket-asg", Map.of( "minCapacity", 2, "instanceType", new InstanceType("c5.large"), "machineImageType", ecs.MachineImageType.getBOTTLEROCKET()));
To add spot instances into the cluster, you must specify the spotPrice
in the ecs.AddCapacityOptions
and optionally enable the spotInstanceDraining
property.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Add an AutoScalingGroup with spot instances to the existing cluster cluster.addCapacity("AsgSpot", Map.of( "maxCapacity", 2, "minCapacity", 2, "desiredCapacity", 2, "instanceType", new InstanceType("c5.xlarge"), "spotPrice", "0.0735", // Enable the Automated Spot Draining support for Amazon ECS "spotInstanceDraining", true));
When the ecs.AddCapacityOptions
that you provide has a non-zero taskDrainTime
(the default) then an SNS topic and Lambda are created to ensure that the
cluster's instances have been properly drained of tasks before terminating. The SNS Topic is sent the instance-terminating lifecycle event from the AutoScalingGroup,
and the Lambda acts on that event. If you wish to engage server-side encryption for this SNS Topic
then you may do so by providing a KMS key for the topicEncryptionKey
propery of ecs.AddCapacityOptions
.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Given Object key = kms.Key(...); // Then, use that key to encrypt the lifecycle-event SNS Topic. cluster.addCapacity("ASGEncryptedSNS", Map.of( "instanceType", new InstanceType("t2.xlarge"), "desiredCapacity", 3, "topicEncryptionKey", key));
A task Definition describes what a single copy of a task should look like. A task definition has one or more containers; typically, it has one main container (the default container is the first one that's added to the task definition, and it is marked essential) and optionally some supporting containers which are used to support the main container, doings things like upload logs or metrics to monitoring services.
To run a task or service with Amazon EC2 launch type, use the Ec2TaskDefinition
. For AWS Fargate tasks/services, use the
FargateTaskDefinition
. These classes provide a simplified API that only contain
properties relevant for that specific launch type.
For a FargateTaskDefinition
, specify the task size (memoryLimitMiB
and cpu
):
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef") .memoryLimitMiB(512) .cpu(256) .build();
To add containers to a task definition, call addContainer()
:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object container = fargateTaskDefinition.addContainer("WebContainer", Map.of( // Use an image from DockerHub "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample")));
For a Ec2TaskDefinition
:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object ec2TaskDefinition = Ec2TaskDefinition.Builder.create(this, "TaskDef") .networkMode(NetworkMode.getBRIDGE()) .build(); Object container = ec2TaskDefinition.addContainer("WebContainer", Map.of( // Use an image from DockerHub "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), "memoryLimitMiB", 1024));
You can specify container properties when you add them to the task definition, or with various methods, e.g.:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 container.addPortMappings(Map.of( "containerPort", 3000));
To add data volumes to a task definition, call addVolume()
:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object volume = ecs.Volume("Volume", Map.of( // Use an Elastic FileSystem "name", "mydatavolume", "efsVolumeConfiguration", ecs.EfsVolumeConfiguration(Map.of( "fileSystemId", "EFS")))); Object container = fargateTaskDefinition.addVolume("mydatavolume");
To use a TaskDefinition that can be used with either Amazon EC2 or
AWS Fargate launch types, use the TaskDefinition
construct.
When creating a task definition you have to specify what kind of tasks you intend to run: Amazon EC2, AWS Fargate, or both. The following example uses both:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object taskDefinition = TaskDefinition.Builder.create(this, "TaskDef") .memoryMiB("512") .cpu("256") .networkMode(NetworkMode.getAWS_VPC()) .compatibility(ecs.Compatibility.getEC2_AND_FARGATE()) .build();
Images supply the software that runs inside the container. Images can be obtained from either DockerHub or from ECR repositories, or built directly from a local Dockerfile.
ecs.ContainerImage.fromRegistry(imageName)
: use a public image.ecs.ContainerImage.fromRegistry(imageName, { credentials: mySecret })
: use a private image that requires credentials.ecs.ContainerImage.fromEcrRepository(repo, tag)
: use the given ECR repository as the image
to start. If no tag is provided, "latest" is assumed.ecs.ContainerImage.fromAsset('./image')
: build and upload an
image directly from a Dockerfile
in your source directory.ecs.ContainerImage.fromDockerImageAsset(asset)
: uses an existing
@aws-cdk/aws-ecr-assets.DockerImageAsset
as a container image.
To pass environment variables to the container, you can use the environment
, environmentFiles
, and secrets
props.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 taskDefinition.addContainer("container", Map.of( "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"), "memoryLimitMiB", 1024, "environment", Map.of(// clear text, not for sensitive data "STAGE", "prod"), "environmentFiles", asList(ecs.EnvironmentFile.fromAsset("./demo-env-file.env"), ecs.EnvironmentFile.fromBucket(s3Bucket, "assets/demo-env-file.env")), "secrets", Map.of(// Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up. "SECRET", ecs.Secret.fromSecretsManager(secret), "DB_PASSWORD", ecs.Secret.fromSecretsManager(dbSecret, "password"), // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks) "PARAMETER", ecs.Secret.fromSsmParameter(parameter))));
The task execution role is automatically granted read permissions on the secrets/parameters. Support for environment files is restricted to the EC2 launch type for files hosted on S3. Further details provided in the AWS documentation about specifying environment variables.
A Service
instantiates a TaskDefinition
on a Cluster
a given number of
times, optionally associating them with a load balancer.
If a task fails,
Amazon ECS automatically restarts the task.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object taskDefinition; Object service = FargateService.Builder.create(this, "Service") .cluster(cluster) .taskDefinition(taskDefinition) .desiredCount(5) .build();
Services
by default will create a security group if not provided.
If you'd like to specify which security groups to use you can override the securityGroups
property.
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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object service = FargateService.Builder.create(stack, "Service") .cluster(cluster) .taskDefinition(taskDefinition) .circuitBreaker(Map.of("rollback", true)) .build();
Services
are load balancing targets and can be added to a target group, which will be attached to an application/network load balancers:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.elasticloadbalancingv2.*; Object service = FargateService.Builder.create(this, "Service").build(); ApplicationLoadBalancer lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps().vpc(vpc).internetFacing(true)); ApplicationListener listener = lb.addListener("Listener", new BaseApplicationListenerProps().port(80)); ApplicationTargetGroup targetGroup1 = listener.addTargets("ECS1", new AddApplicationTargetsProps() .port(80) .targets(asList(service))); ApplicationTargetGroup targetGroup2 = listener.addTargets("ECS2", new AddApplicationTargetsProps() .port(80) .targets(asList(service.loadBalancerTarget(Map.of( "containerName", "MyContainer", "containerPort", 8080)))));
Note that in the example above, the default service
only allows you to register the first essential container or the first mapped port on the container as a target and add it to a new target group. To have more control over which container and port to register as targets, you can use service.loadBalancerTarget()
to return a load balancing target for a specific container and port.
Alternatively, you can also create all load balancer targets to be registered in this service, add them to target groups, and attach target groups to listeners accordingly.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.elasticloadbalancingv2.*; Object service = FargateService.Builder.create(this, "Service").build(); ApplicationLoadBalancer lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps().vpc(vpc).internetFacing(true)); ApplicationListener listener = lb.addListener("Listener", new BaseApplicationListenerProps().port(80)); service.registerLoadBalancerTargets(Map.of( "containerName", "web", "containerPort", 80, "newTargetGroupId", "ECS", "listener", ecs.ListenerConfig.applicationListener(listener, Map.of( "protocol", elbv2.ApplicationProtocol.getHTTPS()))));
If you want to put your Load Balancer and the Service it is load balancing to in
different stacks, you may not be able to use the convenience methods
loadBalancer.addListener()
and listener.addTargets()
.
The reason is that these methods will create resources in the same Stack as the
object they're called on, which may lead to cyclic references between stacks.
Instead, you will have to create an ApplicationListener
in the service stack,
or an empty TargetGroup
in the load balancer stack that you attach your
service to.
See the ecs/cross-stack-load-balancer example for the alternatives.
Services
can also be directly attached to a classic load balancer as targets:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.elasticloadbalancing.*; Object service = Ec2Service.Builder.create(this, "Service").build(); LoadBalancer lb = new LoadBalancer(stack, "LB", new LoadBalancerProps().vpc(vpc)); lb.addListener(new LoadBalancerListener().externalPort(80)); lb.addTarget(service);
Similarly, if you want to have more control over load balancer targeting:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.elasticloadbalancing.*; Object service = Ec2Service.Builder.create(this, "Service").build(); LoadBalancer lb = new LoadBalancer(stack, "LB", new LoadBalancerProps().vpc(vpc)); lb.addListener(new LoadBalancerListener().externalPort(80)); lb.addTarget(service.getLoadBalancerTarget(), Map.of( "containerName", "MyContainer", "containerPort", 80));
There are two higher-level constructs available which include a load balancer for you that can be found in the aws-ecs-patterns module:
LoadBalancedFargateService
LoadBalancedEc2Service
You can configure the task count of a service to match demand. Task auto-scaling is
configured by calling autoScaleTaskCount()
:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object scaling = service.autoScaleTaskCount(Map.of("maxCapacity", 10)); scaling.scaleOnCpuUtilization("CpuScaling", Map.of( "targetUtilizationPercent", 50)); scaling.scaleOnRequestCount("RequestScaling", Map.of( "requestsPerTarget", 10000, "targetGroup", target));
Task auto-scaling is powered by Application Auto-Scaling. See that section for details.
If you're running on AWS Fargate, AWS manages the physical machines that your containers are running on for you. If you're running an Amazon ECS cluster however, your Amazon EC2 instances might fill up as your number of Tasks goes up.
To avoid placement errors, configure auto-scaling for your Amazon EC2 instance group so that your instance count scales with demand. To keep your Amazon EC2 instances halfway loaded, scaling up to a maximum of 30 instances if required:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object autoScalingGroup = cluster.addCapacity("DefaultAutoScalingGroup", Map.of( "instanceType", new InstanceType("t2.xlarge"), "minCapacity", 3, "maxCapacity", 30, "desiredCapacity", 3, // Give instances 5 minutes to drain running tasks when an instance is // terminated. This is the default, turn this off by specifying 0 or // change the timeout up to 900 seconds. "taskDrainTime", Duration.seconds(300))); autoScalingGroup.scaleOnCpuUtilization("KeepCpuHalfwayLoaded", Map.of( "targetUtilizationPercent", 50));
See the @aws-cdk/aws-autoscaling
library for more autoscaling options
you can configure on your instances.
To start an Amazon ECS task on an Amazon EC2-backed Cluster, instantiate an
@aws-cdk/aws-events-targets.EcsTask
instead of an Ec2Service
:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.services.events.targets.*; // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromAsset(path.resolve(__dirname, "..", "eventhandler-image")), "memoryLimitMiB", 256, "logging", AwsLogDriver.Builder.create().streamPrefix("EventDemo").build())); // An Rule that describes the event trigger (in this case a scheduled run) Object rule = Rule.Builder.create(this, "Rule") .schedule(events.Schedule.expression("rate(1 min)")) .build(); // Pass an environment variable to the container 'TheContainer' in the task rule.addTarget(new EcsTask(new EcsTaskProps() .cluster(cluster) .taskDefinition(taskDefinition) .taskCount(1) .containerOverrides(asList(new ContainerOverride() .containerName("TheContainer") .environment(asList(new TaskEnvironmentVariable() .name("I_WAS_TRIGGERED") .value("From CloudWatch Events")))))));
Currently Supported Log Drivers:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.awsLogs(Map.of("streamPrefix", "EventDemo"))));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.fluentd()));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.gelf(Map.of("address", "my-gelf-address"))));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.journald()));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.jsonFile()));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.splunk(Map.of( "token", cdk.SecretValue.secretsManager("my-splunk-token"), "url", "my-splunk-url"))));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.syslog()));
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", ecs.LogDrivers.firelens(Map.of( "options", Map.of( "Name", "firehose", "region", "us-west-2", "delivery_stream", "my-stream")))));
A generic log driver object exists to provide a lower level abstraction of the log driver configuration.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 // Create a Task Definition for the container to start Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef"); taskDefinition.addContainer("TheContainer", Map.of( "image", ecs.ContainerImage.fromRegistry("example-image"), "memoryLimitMiB", 256, "logging", GenericLogDriver.Builder.create() .logDriver("fluentd") .options(Map.of( "tag", "example-tag")) .build()));
Currently, only FARGATE
and FARGATE_SPOT
capacity providers are supported.
To enable capacity providers on your cluster, set the capacityProviders
field
to [FARGATE
, FARGATE_SPOT
]. Then, specify capacity provider strategies on
the capacityProviderStrategies
field for your Fargate Service.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.core.*; import software.amazon.awscdk.services.ec2.*; import lib.*; App app = new App(); Stack stack = new Stack(app, "aws-ecs-integ-capacity-provider"); Vpc vpc = new Vpc(stack, "Vpc", new VpcProps().maxAzs(2)); Object cluster = Cluster.Builder.create(stack, "FargateCPCluster") .vpc(vpc) .capacityProviders(asList("FARGATE", "FARGATE_SPOT")) .build(); Object taskDefinition = new FargateTaskDefinition(stack, "TaskDef"); taskDefinition.addContainer("web", Map.of( "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))); FargateService.Builder.create(stack, "FargateService") .cluster(cluster) .taskDefinition(taskDefinition) .capacityProviderStrategies(asList(Map.of( "capacityProvider", "FARGATE_SPOT", "weight", 2), Map.of( "capacityProvider", "FARGATE", "weight", 1))) .build(); app.synth();
Copyright © 2021. All rights reserved.