logo
Menu
How To Deploy AWS ECS Fargate service using AWS CDK

How To Deploy AWS ECS Fargate service using AWS CDK

In this article, we will deploy a sample web application to an AWS ECS Fargate service using AWS Cloud Development Kit (CDK)

Published Jan 10, 2024

Introduction

What is Fargate?

This article will guide you through the process of deploying Fargate using AWS CDK. According to the official AWS documentation, AWS Fargate is described as a serverless compute engine that operates on a pay-as-you-go model. It enables you to concentrate on developing applications without the need to handle servers directly.
In simpler terms, Fargate allows you to execute containers on ECS in AWS without the burden of server management. This simplifies the overall management process, as there is no need to concern yourself with selecting server types or determining when to scale the cluster. When utilizing Fargate, containers operate seamlessly without the necessity for EC2 instances.

Features of Fargate

Fargate encompasses several distinctive features that set it apart as a unique service. Let's delve into each feature in detail:
  1. Load Balancing:
    • When initiating a Fargate service, if you specify the IP address, it automatically registers with the Load Balancer.
    • This feature ensures efficient distribution of incoming traffic among multiple Fargate instances, enhancing the service's reliability and availability.
  2. Networking:
    • All Fargate tasks operate within a Virtual Private Cloud (VPC).
    • Fargate supports AWS VPC networking mode, providing a secure and isolated environment for the service.
    • Utilizing VPC networking allows for the segregation of services, enabling better control and management.
  3. Configurability Management:
    • Fargate offers extensive configuration options, providing flexibility in adjusting CPU and memory combinations to match specific requirements.
    • The configurable range spans from 2 GB to 8 GB, allowing users to fine-tune the configuration at any given time.
    • This adaptability ensures that the service can be tailored to accommodate varying workloads without compromising performance.
  4. Container Registry Support:
    • Fargate seamlessly integrates with Container Registries, such as Amazon Elastic Container Registry (ECR).
    • The task execution role in Fargate facilitates easy authentication, enabling the pulling of container images from ECR.
    • Additionally, Fargate supports connections to Docker Hub, offering flexibility in managing container images from different sources.
In summary, Fargate's features encompass efficient load balancing, secure networking within VPC, extensive configurability, and seamless support for container registries, collectively contributing to its appeal as a versatile and user-friendly compute engine.

How to deploy fargate using AWS CDK?

Requirements for Setup:

  1. AWS Account:
    • To proceed with the setup, ensure that you have a valid AWS account. This is essential for accessing and utilizing AWS services.
  2. Configured AWS CLI:
    • Make sure that the AWS Command Line Interface (CLI) is properly configured on your system. The AWS CLI is a powerful tool that allows you to interact with various AWS services through the command line.
  3. NPM Package Manager:
    • Install the Node Package Manager (npm) on your system. This package manager is necessary for installing the AWS Cloud Development Kit (CDK), which plays a key role in deploying resources on AWS.
  4. Node.js Installed (Version >14.0.0):
    • Ensure that Node.js is installed on your machine, and the version is greater than 14.0.0. Node.js is required to run JavaScript applications, and having a version above 14.0.0 ensures compatibility with the CDK and its dependencies.
Lets start with steps now.
I will be using my own AWS Account for this article. I intend to execute all tasks using the AWS Cloud9 IDE environment.
AWS CLI Configured as shown below
Cloud9-AWS-CLI-Config
Cloud9-AWS-CLI-Config
Node.js is installed & NPM Package Manager (NPM) comes by defualt with Node.js as shown below
Node-version-with-npm
Node-version-with-npm
Step 1 – Install AWS Cloud Development Kit (CDK)
To install AWS CDK run the below command
1
npm install -g aws-cdk
Installing AWS CDK on AWS Cloud9 environment is unnecessary since the AWS Cloud9 instance already comes prebuilt with it.
Check the AWS CDK version using the below command
1
cdk --version
CDK-Version
CDK-Version
To work with the AWS CDK, you must have an AWS account and credentials and have installed Node.js and the AWS CDK Toolkit. See AWS CDK Prerequisites.
You also need TypeScript itself (version 3.8 or later). If you don't already have it, you can install it using npm.
1
npm install -g typescript
CDK-Typescript
CDK-Typescript
Note
If you get a permission error, and have administrator access on your system, try sudo npm install -g typescript.
Keep TypeScript up to date with a regular npm update -g typescript.

Step 2 – Create a folder for deployment with the basic files

The following commands can be used to create the necessary folder structure:
1
2
mkdir aws-fargate
cd aws-fargate
Now, within the newly created folder, the following files need to be generated:
a. cdk.json file:
  • Purpose: This file instructs the CDK CLI on how to execute the CDK code and keeps track of feature flags for safe deployment of new features and bug fixes.
1
2
3
{
"app": "npx ts-node --prefer-ts-exts main.ts"
}
b. package.json file:
  • Purpose: This npm module manifest includes information about the application, such as its name, version, dependencies, and build scripts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"name": "application-load-balanced-fargate-service",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"cdk": "cdk"
},
"author": {
"name": "Piyush Chaudhari",
"url": "http://piyushchaudhari.com",
"organization": false
},
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^10.17.27",
"typescript": "~3.9.7"
},
"dependencies": {
"aws-cdk-lib": "2.89.0",
"constructs": "^10.2.69"
}
}
  • Explanation: The file includes specifications for the application, such as its name, description, scripts, author, license, and dependencies.
c. main.ts file:
  • Purpose: This TypeScript file contains the main code for the implementation, creating a VPC and instantiating the Fargate Service with a cluster and image.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecspatterns from 'aws-cdk-lib/aws-ecs-patterns';
import * as logs from 'aws-cdk-lib/aws-logs';

export class ECSServiceStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Create a VPC with 9x subnets divided over 3 AZ's
const vpc = new ec2.Vpc(this, 'SkeletonVpc', {
cidr: '172.31.0.0/16',
natGateways: 1,
maxAzs: 3,
subnetConfiguration: [
{
cidrMask: 20,
name: 'public',
subnetType: ec2.SubnetType.PUBLIC,
},
{
cidrMask: 20,
name: 'application',
subnetType: ec2.SubnetType.PRIVATE_WITH_NAT,
},
{
cidrMask: 20,
name: 'data',
subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
},
],
});

// Create an ECS cluster
const cluster = new ecs.Cluster(this, 'service-cluster', {
clusterName: 'service-cluster',
containerInsights: true,
vpc: vpc,
});

// Create a Fargate container image
const image = ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample');

// Create higher level construct containing the Fargate service with a load balancer
new ecspatterns.ApplicationLoadBalancedFargateService(this, 'amazon-ecs-sample', {
cluster,
circuitBreaker: {
rollback: true,
},
memoryLimitMiB: 512, // Supported configurations: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecs_patterns.ApplicationMultipleTargetGroupsFargateService.html#memorylimitmib
cpu: 256,
desiredCount: 1,
taskImageOptions: {
image: image,
containerPort: 80,
logDriver: ecs.LogDrivers.awsLogs({
streamPrefix: id,
logRetention: logs.RetentionDays.ONE_YEAR,
}),
},
});
}
}

const app = new cdk.App();
new ECSServiceStack(app, 'ECSServiceStack');
app.synth();
  • Explanation: The code imports necessary libraries, creates a VPC and Fargate cluster, and pulls an image from the registry to instantiate the Fargate service.
d. tsconfig.json file:
  • Purpose: This file specifies the root files and compiler options required to compile the TypeScript project.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"lib": ["es2018"],
"declaration": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": false,
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"typeRoots": ["./node_modules/@types"]
},
"exclude": ["node_modules", "cdk.out"]
}
  • Explanation: This file outlines compiler options for the TypeScript project, detailing how the project should be compiled.
Folder-Structure
Folder-Structure
These files collectively set up the necessary structure and configuration for the demonstration. To proceed with Fargate deployment, let's move forward.

Step 3 – Deploying the above stack

To initiate the deployment of the mentioned stack, execute the following command in the directory where the files are located:
1
npm install
This command will install all the dependencies specified in the stack file.
npm-install
npm-install
Following the dependencies installation, proceed with the following command:
1
cdk bootstrap
This command prepares the environment by generating the CloudFormation template in AWS. The template encapsulates all the resources to be created during the deployment process.
CDK Bootstrap
CDK Bootstrap
The output indicates the successful bootstrapping of the environment.
After confirming the changes, proceed to deploy the application by running the following command:
1
cdk deploy
This command initiates the deployment of the Fargate service.
CDK-deploy-output-1
CDK-deploy-output-1
CDK-deploy-output-2
CDK-deploy-output-2
The deployment process will unfold, and upon completion, you will observe the deployment confirmation:
CDK-deploy-output-3
CDK-deploy-output-3
The stack has been successfully deployed.
Here is the output reflecting the stack created on AWS.
CDK-CFT-Resources
CDK-CFT-Resources
CDK-CFT-Outputs
CDK-CFT-Outputs
ECS-Fargate-Stack
ECS-Fargate-Stack
Sample Web application has been deployed successfully and is accessible via application load balancer as shown below
Sample-Web-App
Sample-Web-App
NOTE: Remember to execute the "cdk destroy" command afterward, as the resources in use will incur high costs. This ensures proper resource cleanup and cost management.
CDK-destroy
CDK-destroy

The outcomes achieved from the deployment outlined above include:

  1. Automated Load Balancer Configuration:
    • The deployment automatically configures a load balancer, streamlining the process of distributing incoming traffic.
  2. Security Group Creation and Load Balancer Integration:
    • A security group is created, and the load balancer is seamlessly integrated with it to enhance network security.
  3. ECR Permission Setup:
    • Permissions for Amazon Elastic Container Registry (ECR) are established, facilitating secure authentication and image retrieval.
  4. Prevention of Automatic Instance Deletion:
    • Safeguards are implemented to prevent instances from being automatically deleted, ensuring stability and control over resources.
  5. Automated Scaling:
    • The demonstration showcases the achievement of automatic scaling, allowing the system to dynamically adapt to varying workloads for optimal performance.

Conclusion

In conclusion, this discussion demonstrated the ability to execute containers without the necessity of server management. Furthermore, the utilization of Fargate streamlined the entire operation, providing automation. It's noteworthy that Fargate seamlessly integrates with both Elastic Container Service and Elastic Kubernetes Service.
Hope you enjoyed it.

This concludes the present article. Wishing you all a wonderful day! Stay tuned for more updates. Remember to show your support by liking and sharing this post on your social networks. I'll continue to share insights within this fantastic AWS community platform. Please make sure to follow for future content!Let's build a community that thrives on the exchange of knowledge, where collaboration fuels innovation. Join me in this endeavor, and together, let's shape the future of technology.

Comments