- Newest
- Most votes
- Most comments
Hello!
For setting CPU and memory, you can actually do that within the TaskDefinition construct (see TaskDefinition Documentation) which is a more general class. Just specify the cpu and memoryMiB configurations directly there. Then, if you want to run the task on an EC2 cluster, set the compatibility field to Compatibility.EC2 (Compatibility Documentation).
Hope this helps! 😊
When using the EC2TaskDefinition construct in CDK with TypeScript, you can set CPU and memory at both the task level and container level. Here's how to do it:
-
Task Level: For EC2TaskDefinition, you can set the CPU and memory at the task level when creating the task definition:
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef', { cpu: '256', memoryMiB: '512', });The
cpuparameter is specified in CPU units or vCPUs, whilememoryMiBis specified in MiB. -
Container Level: You're correct that you can set CPU and memory when adding a container to the task definition:
taskDefinition.addContainer('MyContainer', { image: ecs.ContainerImage.fromRegistry('my-image'), cpu: 256, memoryLimitMiB: 512, memoryReservationMiB: 256, });Here,
cpuis in CPU units,memoryLimitMiBis the hard limit in MiB, andmemoryReservationMiBis the soft limit.
It's important to note that for EC2 launch type, you must specify either a task-level memory value or a container-level memory value. If you specify a task-level memory value, the container-level memory value is optional.
When using EC2 launch type, you have more flexibility with CPU and memory values compared to Fargate. Any value can be used for CPU, and the memory can be set to any amount that fits within the resources of the underlying EC2 instance.
Remember that the total CPU and memory reserved for all containers within a task should not exceed the task-level CPU and memory values. If you're using task-level resource allocation, ensure that the values you set are appropriate for the EC2 instance types in your ECS cluster.
Sources
class CfnTaskDefinition (construct) · AWS CDK
class TaskDefinition (construct) · AWS CDK
Troubleshoot Amazon ECS task definition invalid CPU or memory errors - Amazon Elastic Container Service
There is definitly no cpu and memory in the Ex2TaskDefinition construct. https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs.Ec2TaskDefinition.html
answered 2 years ago
Relevant content
asked 2 years ago
asked 2 years ago
asked 3 years ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated a year ago

Like user jfsandri suggests, try using the Task Definition Construct rather than the EC2 Task Definition Construct. The Task Definition Construct will still work with running tasks on EC2-based services in ECS.