Using AWS CDK to Deploy an AWS Fargate Service

Using AWS CDK to Deploy an AWS Fargate Service

Introduction

Amazon Web Services (AWS) offers a wide range of tools and services for developers to build, deploy, and manage their applications in the cloud. One such service is AWS Fargate, a serverless compute engine for containers that make it easier to run containerized applications without managing the underlying infrastructure. The AWS Cloud Development Kit (CDK) is an open-source software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation.

This blog post will dive deep into using the AWS CDK to deploy an AWS Fargate service, complete with code examples. By the end of this guide, you will better understand how to deploy a containerized application using the AWS CDK and Fargate.

Prerequisites

Before getting started, make sure you have the following installed and configured:

  1. Node.js (v10.x or later)

  2. AWS CLI (v2.x)

  3. AWS CDK (v2.x)

  4. Docker (for building and testing the container)

Get Started

Step 1: Initialize the AWS CDK project

First, create a new directory for your project and initialize a new CDK project using TypeScript:

$ mkdir fargate-cdk && cd fargate-cdk
$ cdk init --language typescript

Step 2: Open in VSCode or any editor

In VSCode:

$ code .

Step 3: Define the Fargate service stack

Open the lib/fargate-cdk-stack.ts file and replace its content with the following code:

import * as cdk from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as ecs_patterns from 'aws-cdk-lib/aws-ecs-patterns';

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

    // Create an ECS cluster
    const cluster = new ecs.Cluster(this, 'FargateCluster', {
      vpc: new cdk.Vpc(this, 'Vpc'),
    });

    // Load the ECR repository
    const ecrRepository = ecr.Repository.fromRepositoryName(
      this,
      'EcrRepository',
      'your-ecr-repo-name'
    );

    // Define the Fargate service
    new ecs_patterns.ApplicationLoadBalancedFargateService(this, 'FargateService', {
      cluster: cluster,
      taskImageOptions: {
        image: ecs.ContainerImage.fromEcrRepository(ecrRepository),
        containerPort: 80,
      },
      desiredCount: 2,
      publicLoadBalancer: true,
    });
  }
}

Replace 'your-ecr-repo-name' with the name of your existing ECR repository.

Step 4: Build the Docker image and push it to ECR

Create a Dockerfile in your project's root directory:

FROM node:14-alpine

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 80

CMD [ "npm", "start" ]

Build the Docker image and push it to your ECR repository:

$ aws ecr --region us-west-2 get-login-password | docker login --username AWS --password-stdin <your_account_id>.dkr.ecr.us-east-1.amazonaws.com

$ docker build -t your-ecr-repo-name .

$ docker tag your-ecr-repo-name:latest <your_account_id>.dkr.ecr.us-east-1.amazonaws.com/your-ecr-repo-name:latest

$ docker push <your_account_id>.dkr.ecr.us-east-1.amazonaws.com/your-ecr-repo-name:latest

Replace <your_account_id> with your AWS account ID.

Step 5: Deploy the Fargate service

Now that you have the Docker image pushed to ECR, you can deploy the Fargate service using the AWS CDK:

$ npm run build
$ cdk deploy

The cdk deploy command will create a new CloudFormation stack with the specified Fargate service, load balancer, and other required resources. You can view the progress of the deployment in the AWS Management Console under the CloudFormation service.

Note: If you're using CDK for the first time make sure to bootstrap your environment.

$ cdk bootstrap

Step 6: Test the Fargate service

After the deployment has been completed, you can test your Fargate service by navigating to the provided load balancer URL. You can find the URL in the CloudFormation stack outputs or the AWS Management Console under the Elastic Load Balancing service.

Conclusion

In this blog post, we have demonstrated how to use the AWS CDK to deploy a containerized application with an AWS Fargate service. By leveraging the AWS CDK and Fargate, you can simplify the deployment and management of your applications, allowing you to focus on writing code rather than managing infrastructure.

Did you find this article valuable?

Support Mikaeel Khalid by becoming a sponsor. Any amount is appreciated!