
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)
- 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.
- 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.
- 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.
- 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.
- AWS Account:
- To proceed with the setup, ensure that you have a valid AWS account. This is essential for accessing and utilizing AWS services.
- 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.
- 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.
- 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.
1
npm install -g aws-cdk
1
cdk --version
npm
.1
npm install -g typescript
sudo npm install -g typescript
.npm update -g typescript
.1
2
mkdir aws-fargate
cd aws-fargate
- 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"
}
- 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.
- 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.
- 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.
1
npm install
1
cdk bootstrap
1
cdk deploy
- Automated Load Balancer Configuration:
- The deployment automatically configures a load balancer, streamlining the process of distributing incoming traffic.
- 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.
- ECR Permission Setup:
- Permissions for Amazon Elastic Container Registry (ECR) are established, facilitating secure authentication and image retrieval.
- Prevention of Automatic Instance Deletion:
- Safeguards are implemented to prevent instances from being automatically deleted, ensuring stability and control over resources.
- Automated Scaling:
- The demonstration showcases the achievement of automatic scaling, allowing the system to dynamically adapt to varying workloads for optimal performance.