exanubes

Application on ECS #1Deploying ECS Fargate Application

This article is part of a series:

  1. Deploying ECS Fargate Application
  2. Adding SSL Certificate to Fargate app
  3. CI/CD pipeline for ECS application
  4. Connecting to RDS via Parameter Store config

In this article we will build and deploy a simple NestJS application on ECS Fargate. To do that we will upload a Docker Image to our ECR Repository. Then we'll create a simple vpc where we will put our application. Next, we will go ahead and create ECS Cluster which will spin-up a Fargate Service from a Task Definition which will be using the aforementioned Docker Image. After all this, we will setup a Load Balancer that will be listening on port 80 and redirecting all traffic to a Target Group which will have our ECS Task instances automatically registered as targets of the Load Balancer.

You can find the finished code on Github

ECR Stack #

First off, we need a repository for the Docker image of our application. We need to do this first because later ECS Service will be pulling this image in order to start a task.

typescript
Double click to copy
1// lib/ecr.stack.ts
2export class EcrStack extends Stack {
3 public readonly repository: IRepository;
4
5 constructor(app: Construct, id: string, props: StackProps) {
6 super(app, id, props);
7 this.repository = new Repository(this, 'exanubes-repository', {
8 imageScanOnPush: false,
9 removalPolicy: RemovalPolicy.DESTROY,
10 });
11 }
12}

All we do here is create a ECR Repo. The imageScanOnPush option would look for vulnerabilities in our image but we don't need it right now so it's turned off.

Now we can put it in the bin file...

typescript
Double click to copy
1//bin/infrastructure.ts
2const app = new cdk.App();
3const ecr = new EcrStack(app, EcrStack.name, {});

...and deploy

Double click to copy
npm run build && npm run cdk:deploy -- --all

Uploading a Docker Image #

Now, if you go to ECR in the AWS Console and check your repository, you should have a View push commands button in the top right corner. Go to your application directory where you have a Dockerfile – or use nest app from the repo – and follow these instructions with one caveat. We will be deploying ECS Fargate with the ARM64 architecture as it is cheaper, so unless you have a computer with a ARM64 processor e.g., Apple Silicone, you will have to change the second step to:

Double click to copy
docker buildx build --platform="linux/arm64" -t <image-tag> .

When successful you should see your docker image in ECR as so:

Uploaded docker image on ECR

VPC Stack #

Before getting started on the ECS, first we need to create a VPC to put it in. We could – of course – use the default VPC for this as well.

typescript
Double click to copy
1// lib/vpc.stack.ts
2export class VpcStack extends Stack {
3 public readonly vpc: IVpc;
4 constructor(scope: Construct, id: string, props: StackProps) {
5 super(scope, id, props);
6 this.vpc = new Vpc(this, 'exanubes-vpc', {
7 cidr: '10.100.0.0/16',
8 maxAzs: 2,
9 subnetConfiguration: [
10 {
11 name: 'public-1',
12 cidrMask: 24,
13 subnetType: SubnetType.PUBLIC,
14 },
15 {
16 name: 'private-1',
17 cidrMask: 24,
18 subnetType: SubnetType.PRIVATE_WITH_NAT,
19 },
20 ],
21 });
22 }
23}

We're defining here a 10.100.0.0 with the size 16 CIDR block – this basically means that the first 16 bits are locked and the other 16 bits are available for us to use, so essentially we have 255*255 IP addresses available to us. Selecting only two azs to have high availability – one would also be fine for this – and defining only one public and private subnet for each AZ – so we will have 4 in total.

Worth noticing is that we assigned the vpc to a property on the class instance, that's because we will want to pass that vpc to our ECS Cluster later.

ECS Stack #

First off, we gotta create a cluster, which is just a logical grouping of tasks and services. All the tasks and services are running on an infrastructure registered to a cluster. When separating resources, we'd want to deploy multiple clusters.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2
3interface Props extends StackProps {
4 vpc: IVpc;
5 repository: IRepository;
6}
7
8const CONTAINER_PORT = 8081;
9
10export class ElasticContainerStack extends Stack {
11 constructor(scope: Construct, id: string, private readonly props: Props) {
12 super(scope, id, props);
13 const cluster = new Cluster(this, 'exanubes-cluster', {
14 vpc: props.vpc,
15 clusterName: 'exanubes-cluster',
16 containerInsights: true,
17 });
18 }
19}

Here, we're creating a cluster and putting it inside the VPC we created earlier. Container Insights are CloudWatch performance logs that will be collected which we can later aggregate and analyze to see how our containers perform.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2
3const albSg = new SecurityGroup(this, 'security-group-load-balancer', {
4 vpc: props.vpc,
5 allowAllOutbound: true,
6});
7
8const loadBalancer = new ApplicationLoadBalancer(this, 'exanubes-alb', {
9 vpc: props.vpc,
10 loadBalancerName: 'exanubes-ecs-alb',
11 internetFacing: true,
12 idleTimeout: Duration.minutes(10),
13 securityGroup: albSg,
14 http2Enabled: false,
15 deletionProtection: false,
16});

Next, we need an Application Load Balancer(ALB) and a security group(SG) for it. CDK would create a default SG but we will then need to allow traffic from it to the ECS Service, so I prefer to create it explicitly. ALB will also be placed inside our VPC and most importantly we need to have it open to the internet – internet facing. Deletion Protection ensures that no one removes a load balancer by accident as it first needs to be disabled before being deleting when protection's enabled.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2const httpListener = loadBalancer.addListener('http listener', {
3 port: 80,
4 open: true,
5});
6
7const targetGroup = httpListener.addTargets('tcp-listener-target', {
8 targetGroupName: 'tcp-target-ecs-service',
9 protocol: ApplicationProtocol.HTTP,
10 protocolVersion: ApplicationProtocolVersion.HTTP1,
11});

When users visit our domain they will actually hit the load balancer which then needs to know how to reach our application. We achieve this with listeners and target groups. A listener tells the load balancer on what port it should expect traffic, then it has three options - forward, redirect or custom response. We can also define rules and depending on headers, request methods, path or query strings we can tell the Load Balancer to route to a different target group. Whereas target group routes requests to registered targets – which in our case will be the ECS Fargate Task.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2const taskDefinition = new FargateTaskDefinition(
3 this,
4 'fargate-task-definition',
5 {
6 runtimePlatform: {
7 cpuArchitecture: CpuArchitecture.ARM64,
8 operatingSystemFamily: OperatingSystemFamily.LINUX,
9 },
10 }
11);
12const container = taskDefinition.addContainer('web-server', {
13 image: EcrImage.fromEcrRepository(props.repository),
14});
15container.addPortMappings({
16 containerPort: CONTAINER_PORT,
17});

Now it's finally time to create our Task Definition. This is similar to a Docker Image, which is an instruction manual on how to build and run the application. Task definition is a manual on how to perform a task, which and how many containers to use, how much CPU and memory etc. A task definition is also where we define what architecture – or runtime platform – we'd like to use. Because it's significantly cheaper, we opt for Linux OS on ARM64 machine.

When creating a container, we also have to tell ECS what port it's going to run on – this should be the same port we expose in the Dockerfile.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2
3const securityGroup = new SecurityGroup(this, 'http-sg', {
4 vpc: props.vpc,
5});
6securityGroup.addIngressRule(
7 Peer.securityGroupId(albSg.securityGroupId),
8 Port.tcp(CONTAINER_PORT),
9 'Allow inbound connections from ALB'
10);
11const fargateService = new FargateService(this, 'fargate-service', {
12 cluster,
13 assignPublicIp: false,
14 taskDefinition,
15 securityGroups: [securityGroup],
16 desiredCount: 1,
17});

Nearing the end, we can finally create an ECS Service. The difference between tasks and services are that a task does a finite job and then exits, whereas service is more for infinite tasks like a web server for example. We need to define which cluster the service belongs to and what task definition it's supposed to use to spin-up tasks. We can also opt-out of assigning public IP addresses as we won't be needing those. Desired count is the minimum amount of tasks that the service will attempt to keep running at all times. We choose 1 to keep the costs low, make sure you don't put some ridiculously large number here as it could cost you a lot of money.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2
3targetGroup.addTarget(fargateService);

Last but not least, a very important step. We're adding the ECS Service as target to the target group. Thanks to this, target group will automatically register all new Tasks and make them available to the load balancer and thus, the end user.

All of ElasticContainerStack #

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2interface Props extends StackProps {
3 vpc: IVpc
4 repository: IRepository
5}
6
7const CONTAINER_PORT = 8081
8
9export class ElasticContainerStack extends Stack {
10
11 constructor(scope: Construct, id: string, private readonly props: Props) {
12 super(scope, id, props);
13 const cluster = new Cluster(this, 'exanubes-cluster', {
14 vpc: props.vpc,
15 clusterName: 'exanubes-cluster',
16 containerInsights: true,
17 enableFargateCapacityProviders: true,
18 })
19 const albSg = new SecurityGroup(this, 'security-group-load-balancer', {
20 vpc: props.vpc,
21 allowAllOutbound: true
22 })
23
24 const loadBalancer = new ApplicationLoadBalancer(this, 'exanubes-alb', {
25 vpc: props.vpc,
26 loadBalancerName: 'exanubes-ecs-application-LB',
27 internetFacing: true,
28 idleTimeout: Duration.minutes(10),
29 securityGroup: albSg,
30 http2Enabled: false,
31 deletionProtection: false
32 })
33
34 const httpListener = loadBalancer.addListener("http listener", {
35 port: 80,
36 open: true,
37 })
38
39 const targetGroup = httpListener.addTargets("tcp-listener-target", {
40 targetGroupName: "tcp-target-ecs-service",
41 protocol: ApplicationProtocol.HTTP,
42 protocolVersion: ApplicationProtocolVersion.HTTP1,
43 })
44
45 const taskDefinition = new FargateTaskDefinition(this, 'fargate-task-definition', {
46 runtimePlatform: {
47 cpuArchitecture: CpuArchitecture.ARM64,
48 operatingSystemFamily: OperatingSystemFamily.LINUX
49 }
50 });
51 const container = taskDefinition.addContainer('web-server', {
52 image: EcrImage.fromEcrRepository(props.repository),
53 })
54 container.addPortMappings({
55 containerPort: CONTAINER_PORT
56 })
57 const securityGroup = new SecurityGroup(this, 'http-sg', {
58 vpc: props.vpc,
59 })
60 securityGroup.addIngressRule(Peer.securityGroupId(albSg.securityGroupId), CONTAINER_PORT, 'Allow inbound connections from ALB')
61 const fargateService = new FargateService(this, 'fargate-service', {
62 cluster: cluster,
63 assignPublicIp: true,
64 taskDefinition,
65 securityGroups: [securityGroup],
66 desiredCount: 1
67 })
68 targetGroup.addTarget(fargateService)
69 }

Accessing Load Balancer DNS #

Now that everything is setup you can go to AWS Console > EC2 > Load Balancers and copy/paste the LB URL, however, for some reason this does not work right now. Could not figure why though so I have a stack overflow question open. This seems to be a common problem from what I could see when researching this and it's always the same – problem with port 80.

Anyway, we can still checkout our app by changing our Load Balancer listener for the container port and also allowing traffic for that port in the Load Balancer Security Group.

typescript
Double click to copy
1// lib/elastic-container.stack.ts
2albSg.addIngressRule(Peer.anyIpv4(), Port.tcp(CONTAINER_PORT));
3
4const httpListener = loadBalancer.addListener('http listener', {
5 port: CONTAINER_PORT,
6 open: true,
7});

After changing this in our infrastructure, we should be able to go to load-balancer-dns-example-url.com:YOUR_CONTAINER_PORT.

Image of Nestjs app on Load Balancer DNS

Deployment #

Now it's time to create our stacks and deploy

typescript
Double click to copy
1// bin/infrastructure.ts
2const app = new cdk.App();
3const ecr = new EcrStack(app, EcrStack.name, {});
4const vpc = new VpcStack(app, VpcStack.name, {});
5new ElasticContainerStack(app, ElasticContainerStack.name, {
6 vpc: vpc.vpc,
7 repository: ecr.repository,
8});

Deploy:

Double click to copy
npm run build && npm run cdk:deploy -- --all

And don't forget to tear it down when you're done:

Double click to copy
npm run cdk:destroy -- --all

Summary #

In this article we've gone over the most important components of an ECS Fargate application. We created a cluster – which is a logical grouping of tasks and services – inside our custom VPC. Provided instructions on how our app should function in the Task Definition and instructed how many Tasks we want when creating the Fargate Service. We were also able to connect to the app by using a load balancer which thanks to its listeners is able to route traffic via a Target Group which automatically registers every new Task in our Service.

Worth noting is that aws-cdk team have prepared for us an ApplicationLoadBalancedFargateService Construct that will set it all up for us as well.

In the next article, we will go over how to setup SSL certificate for our application with a custom domain.

Thanks!

A verification email has been sent to

Keep in Touch

Join other developers in Exanubes Newsletter

© 2022