Search code examples
typescriptamazon-web-servicesamazon-ecsaws-cdk

Deploying ECS with CDK


I have been going at it now for a day and just cant get ECS to deploy using EC2, I am getting this error

service prod-ecsStack-EC2Service5392EF94-71wVDsfHgsZh was unable to place a task because no container instance met all of its requirements. Reason: No Container Instances were found in your cluster. For more information, see the Troubleshooting section of the Amazon ECS Developer Guide.

I am fairly certain that my container is smaller CPU and memory allocation in task definition. I am using a t2.small to be safe atm, but I want to use the smallest possible instance later.

ECR has the container repo and it is built using the correct architecture.

This is my CDK code right now. Thanks-you

const vpc = new ec2.Vpc(this, 'PersonalWebsiteVpc', {
    maxAzs: 2,
});

const cluster = new ecs.Cluster(this, 'PersonalWebsiteCluster', {
    vpc: vpc
});

const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
    vpc,
    instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.SMALL),
    machineImage: new ec2.AmazonLinuxImage(),
    minCapacity: 1,
    maxCapacity: 2
});

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
    autoScalingGroup: autoScalingGroup,
});

cluster.addAsgCapacityProvider(capacityProvider);

const repository = ecr.Repository.fromRepositoryName(this, 'MyRepository', 'my-personal-website-repo');

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

const container = taskDefinition.addContainer('web', {
    image: ecs.ContainerImage.fromEcrRepository(repository, 'latest'),
    memoryLimitMiB: 1024,
    cpu: 512,
});

container.addPortMappings({
    containerPort: 80,
    hostPort: 80
});

new ecs.Ec2Service(this, 'EC2Service', {
    cluster,
    taskDefinition,
});

Solution

  • The EC2 instance has to have the ECS agent installed. Use the ecs.EcsOptimizedImage as the machineImage prop instead of the generic AMI.