Creating an Amazon ECS Service with AutoScaling and expose it using an Application Load Balancer

8.1. In lib/cdk-msg-app-backend-stack.ts, add the following below the last import.

import * as ecs_patterns from '@aws-cdk/aws-ecs-patterns';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';

8.2. In lib/cdk-msg-app-backend-stack.ts, add the following code inside the constructor to create the Fargate Service with Auto Scaling.

    const sg_service = new ec2.SecurityGroup(this, 'MySGService', { vpc: vpc });
    sg_service.addIngressRule(ec2.Peer.ipv4('0.0.0.0/0'), ec2.Port.tcp(3000));
    
    const service = new ecs.FargateService(this, 'Service', {
      cluster,
      taskDefinition: fargateTaskDefinition,
      desiredCount: 2,
      assignPublicIp: false,
      securityGroup: sg_service
    });
    
    // Setup AutoScaling policy
    const scaling = service.autoScaleTaskCount({ maxCapacity: 6, minCapacity: 2 });
    scaling.scaleOnCpuUtilization('CpuScaling', {
      targetUtilizationPercent: 50,
      scaleInCooldown: cdk.Duration.seconds(60),
      scaleOutCooldown: cdk.Duration.seconds(60)
    });

8.3. In lib/cdk-msg-app-backend-stack.ts, add the following code inside the constructor to create the Application Load Balancer and the Fargate Service associated.

    const lb = new elbv2.ApplicationLoadBalancer(this, 'ALB', {
      vpc,
      internetFacing: true
    });

    const listener = lb.addListener('Listener', {
      port: 80,
    });

    listener.addTargets('Target', {
      port: 80,
      targets: [service],
      healthCheck: { path: '/api/' }
    });

    listener.connections.allowDefaultPortFromAnyIpv4('Open to the world');

8.4. Save it and make sure it builds and creates a stack.

npm run build
cdk synth

8.5. Deploy the stack.

cdk deploy
  • Do you wish to deploy these changes (y/n)? y

8.6. Open the Amazon ECS console on Clusters https://console.aws.amazon.com/ecs/, explore your cluster, you will see a service running with 2 tasks.

ECS Service Tasks

8.7. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/].

8.8. In the navigation pane, under LOAD BALANCING, choose Load Balancers.

8.9. Select the backend balancer, in the Description section copy the DNS Name to test in your browser. you will see the code of the AWS Region you are using.

ALB List

8.10. Test the DNS Name with /api/messages to see the messages.

ECS ALB