iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💡

Building ECS (Fargate) + RDS in Multi-AZ with AWS CDK

に公開
2025/11/08

1. Article Overview

In this article, as an AWS beginner who has started using CDK, I will describe how I built ECS (Fargate) + RDS while considering resource and network configurations.

1.1. Goal

The main goal of this article is to understand the basic configuration of ECS (Fargate) and RDS using AWS CDK and to acquire the skills to actually build them.
By building the environment shown in the architecture diagram below, I aim to experience the fundamentals of IaC and the development workflow, taking a step forward into CDK development.

1.2. Architecture Diagram

The environment to be built this time is as follows.
aws-architecture-diagram.png

ECS functions as a web application server, and requests to the server are made through ALB.

Also, connections to ECR / CloudWatch / S3 / Secrets Manager use VPC Endpoints instead of a NAT Gateway.
The reason for choosing VPC Endpoints is that NAT Gateway is more expensive than VPC Endpoints, and VPC Endpoints provide sufficient functionality for the "connection between ECS and ECR / CloudWatch / S3 / Secrets Manager" that I want to achieve this time.

1.3. Steps

We will build the above configuration using the following steps:

  1. Create ECR repository
  2. Create VPC
  3. Create ALB
  4. Create RDS
  5. Create ECS

Application code and Dockerfile contents are omitted as they diverge from the essence of this article.
Details of the application code are provided in the GitHub link below!

Application code
Dockerfile

2. Implementation

2.1. Overall Approach

Before diving into specific implementation, let's consider the overall strategy.
This time, I'm following a policy of creating a Construct for each AWS resource and linking those Constructs within the Stack.
Since the configuration is not that large, it is possible to write all Constructs directly in the Stack without separating them into classes, but I chose this approach to improve readability and clarify the connections between resources.
Ultimately, I want to achieve interactions between Constructs through the Stack like this:

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

    // ECR
    const ecr = new Ecr(/** some properties */);

    // VPC
    const vpc = new Vpc(/** some properties */);

    // ALB
    const alb = new Alb(/** some properties */);

    // RDS
    const rds = new Rds(/** some properties */);

    // ECS (Fargate)
    const ecs = new Ecs(/** some properties */);
  }
}

Also, the directory structure is planned as follows:

./lib/
├── constructs
│   ├── alb.ts
│   ├── ecs.ts
│   ├── ...etc
└── sample-node-app-stack.ts

2.2. Creating the ECR Repository

First, create the ECR repository.

2.2.1. Defining the ECR Construct

To create the ECR repository, in addition to the L2 constructs included in the CDK library, I use a library called cdk-ecr-deployment.

https://github.com/cdklabs/cdk-ecr-deployment

This library allows Docker images configured with CDK to be saved to any repository.

The complete code is shown below:

lib/construct/ecr.ts
import path from "node:path";

import { IgnoreMode, RemovalPolicy } from "aws-cdk-lib";
import {
  IRepository,
  Repository,
  RepositoryEncryption,
  TagMutability,
} from "aws-cdk-lib/aws-ecr";
import { DockerImageAsset, Platform } from "aws-cdk-lib/aws-ecr-assets";
import { DockerImageName, ECRDeployment } from "cdk-ecr-deployment";
import { Construct } from "constructs";

export class Ecr extends Construct {
  public readonly repository: IRepository;

  constructor(scope: Construct, id: string) {
    super(scope, id);

    this.repository = new Repository(this, "Repository", {
      imageTagMutability: TagMutability.MUTABLE,
      encryption: RepositoryEncryption.AES_256,
      removalPolicy: RemovalPolicy.DESTROY,
      emptyOnDelete: true,
    });

    const image = new DockerImageAsset(this, "Image", {
      directory: path.join(__dirname, "../../"), // Specify the directory containing the Dockerfile
      platform: Platform.LINUX_ARM64,
      // NOTE: Exclude directories/files listed in `.dockerignore` from the upload
      ignoreMode: IgnoreMode.DOCKER,
    });

    new ECRDeployment(this, "DeployDockerImage", {
      src: new DockerImageName(image.imageUri),
      dest: new DockerImageName(`${this.repository.repositoryUri}:latest`),
    });
  }
}

2.2.2. Instantiating the Created Construct Class in the Stack

With the ECR Construct completed, instantiate it in the Stack as follows so it can coordinate with other Constructs through the Stack.

lib/sample-node-app-stack.ts
import type { StackProps } from "aws-cdk-lib";
import { Stack } from "aws-cdk-lib";
import type { Construct } from "constructs";
import { Ecr } from "./construct/ecr";

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

    // ECR
    const ecr = new Ecr(this, "Ecr");
  }
}

2.3. Creating the VPC

Next, create a VPC using the CDK L2 construct.
As shown in the architecture diagram above, we will configure one public subnet and one private subnet in a multi-AZ setup.

2.3.1. Defining the VPC Construct

Define the VPC construct as follows:

lib/construct/vpc.ts
import { IVpc, IpAddresses, SubnetType, Vpc as _Vpc } from "aws-cdk-lib/aws-ec2";
import { Construct } from "constructs";

export class Vpc extends Construct {
  // NOTE: Make it accessible from other stacks
  public readonly resource: IVpc;

  constructor(scope: Construct, id: string) {
    super(scope, id);

    this.resource = new _Vpc(this, "Vpc", {
      availabilityZones: ["ap-northeast-1a", "ap-northeast-1c"],
      // NOTE: Network address part: 16-bit, Host address part: 16-bit
      ipAddresses: IpAddresses.cidr("192.168.0.0/16"),
      subnetConfiguration: [
        {
          name: "public",
          cidrMask: 26, // Since it's small scale, `/26` is sufficient (Network: 26-bit, Host: 6-bit)
          subnetType: SubnetType.PUBLIC,
        },
        // NOTE: Since communication with the outside is done via ALB (not NAT Gateway), specify ISOLATED (connections to ECR use VPC endpoints)
        {
          name: "isolated",
          cidrMask: 26,
          subnetType: SubnetType.PRIVATE_ISOLATED,
        },
      ],
      natGateways: 0,
      createInternetGateway: true,
    });
  }
}

Here is an explanation of the IP Address (CIDR) and Subnet Types.

  • About IP Address (CIDR)
    Following the recommendations in the official documentation, the IP Address (CIDR) is set to 192.168.0.0/16
    (Network address part: 16 bits, Host address part: 16 bits)
    Additionally, since I want to avoid generating unnecessary private IP addresses as much as possible, the CIDR mask is set to 26 (Network address part: 26 bits, Host address part: 6 bits).
    In actual operations, a slightly larger CIDR mask might be better considering potential scaling.

  • About Subnet Types
    Since neither private subnet will communicate directly with the outside and a NAT Gateway is not required, the subnet type is specified as PRIVATE_ISOLATED.
    I referred to the following documentation regarding subnet types:
    enum SubnetType · AWS CDK

2.3.2. Creating VPC Endpoints

As shown in the architecture diagram above, we will create VPC endpoints for S3, CloudWatch, ECR, and Secrets Manager.
VPC endpoints come in two types: Gateway and Interface. Among those mentioned above, S3 is a Gateway type, while CloudWatch, ECR, and Secrets Manager are Interface types, so we will create each according to its specific type.

(I referred to the following documentation for each type:)
AWS PrivateLink concepts - Amazon Virtual Private Cloud

Modify the code as follows:

lib/construct/vpc.ts
+ import {
+   GatewayVpcEndpointAwsService,
+   IVpc,
+   InterfaceVpcEndpointAwsService,
+   IpAddresses,
+   SubnetType,
+   Vpc as _Vpc
+ } from "aws-cdk-lib/aws-ec2"
- import { IpAddresses, SubnetType, Vpc as _Vpc } from "aws-cdk-lib/aws-ec2";
import { Construct } from "constructs";

export class Vpc extends Construct {
   /** Omitted */
  constructor(scope: Construct, id: string) {
    super(scope, id);

    this.resource = new _Vpc(this, "Vpc", {
      /** Omitted */
    });

+   // NOTE: Create VPC endpoints
+   this.resource.addInterfaceEndpoint("EcrEndpoint", {
+     service: InterfaceVpcEndpointAwsService.ECR,
+   });
+   this.resource.addInterfaceEndpoint("EcrDkrEndpoint", {
+     service: InterfaceVpcEndpointAwsService.ECR_DOCKER,
+   });
+   this.resource.addInterfaceEndpoint("CwLogsEndpoint", {
+     service: InterfaceVpcEndpointAwsService.CLOUDWATCH_LOGS,
+   });
+   this.resource.addInterfaceEndpoint("SecretsManagerEndpoint", {
+     service: InterfaceVpcEndpointAwsService.SECRETS_MANAGER,
+   });
+   this.resource.addGatewayEndpoint("S3Endpoint", {
+     service: GatewayVpcEndpointAwsService.S3,
+     subnets: [
+       {
+         subnets: this.resource.isolatedSubnets,
+       },
+     ],
+   });
  }
}

2.3.3. Instantiating the Created Construct Class in the Stack

Through the steps so far, the VPC Construct is now complete. Instantiate the Construct in the Stack as follows so that it can coordinate with other Constructs through the Stack.

lib/sample-node-app-stack.ts
import type { StackProps } from "aws-cdk-lib";
import { Stack } from "aws-cdk-lib";
import type { Construct } from "constructs";
import { Ecr } from "./constructs/ecr";
import { Vpc } from "./construct/vpc";

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

    // ECR
    const ecr = new Ecr(this, "Ecr");

    // VPC
    const vpc = new Vpc(this, "Vpc");
  }
}

2.4. Creating the ALB

2.4.1. Implementing the ALB Construct

As shown in the architecture diagram above, the ALB is placed in the public subnet.
In this configuration, the target for the ALB will be ECS. Since the communication between the ALB and ECS is via HTTP, we specify HTTP as the protocol.
The communication between the ALB and ECS can be visualized as follows.

alb-ecs.drawio.png

The complete code is as follows:

lib/construct/alb.ts
import { IConnectable, SubnetType, type IVpc } from "aws-cdk-lib/aws-ec2";
import type { IApplicationLoadBalancer } from "aws-cdk-lib/aws-elasticloadbalancingv2";
import {
  ApplicationLoadBalancer,
  ApplicationProtocol,
  ApplicationTargetGroup,
  Protocol,
  TargetType,
} from "aws-cdk-lib/aws-elasticloadbalancingv2";
import { Construct } from "constructs";

interface AlbProps {
  vpc: Vpc;
  resourceName: string;
  securityGroup: SecurityGroup;
  subnets: SubnetSelection;
}

export class Alb extends Construct {
  /**
   * Connectable ALB instance
   * @example When connecting a resource to the ALB, use this instance as follows:
   * ```typescript
   * // Specify the resource you want to connect to in the argument of `allowDefaultPortTo`
   * connectableInstance.connections.allowDefaultPortTo(ecsService);
   * ```
   */
  public readonly connectableInstance: IConnectable;

  private readonly resource: IApplicationLoadBalancer;

  constructor(scope: Construct, id: string, props: AlbProps) {
    super(scope, id);

    // NOTE: Create the target group
    const targetGroup = new ApplicationTargetGroup(this, "AlbTargetGroup", {
      vpc: props.vpc,
      targetType: TargetType.IP,
      protocol: ApplicationProtocol.HTTP,
      port: 80,
      healthCheck: {
        path: "/",
        port: "80",
        protocol: Protocol.HTTP,
        healthyHttpCodes: "200",
      },
    });

    // NOTE: Create the ALB
    this.resource = new ApplicationLoadBalancer(this, "Alb", {
      vpc: props.vpc,
      internetFacing: true,
      vpcSubnets: props.vpc.selectSubnets({ subnetType: SubnetType.PUBLIC }),
    });

    // NOTE: Create the listener
    this.resource.addListener("AlbListener", {
      protocol: ApplicationProtocol.HTTP,
      defaultTargetGroups: [targetGroup],
    });

    this.connectableInstance = this.resource;
  }
}

In the code above, the connectableInstance of type IConnectable is exposed as a public variable.
By using this connectableInstance, you can connect the ALB and ECS by writing the code as follows:

alb.connectableInstance.connections.allowDefaultPortTo(ecsService);

2.4.2. Enabling External Target Registration

As mentioned above, in this configuration, ECS serves as the target for the ALB.
Registration of this target is performed using the listener as follows:

alb.listener.addTargets("Ecs", {
  /** Omitted */
});

To enable this through the Stack, we make it possible to retrieve the listener from outside the construct.

lib/construct/alb.ts
- import type { IApplicationLoadBalancer } from "aws-cdk-lib/aws-elasticloadbalancingv2";
+ import type {
+   IApplicationListener,
+   IApplicationLoadBalancer,
+ } from "aws-cdk-lib/aws-elasticloadbalancingv2";

export class Alb extends Construct {
  public readonly value: ApplicationLoadBalancer;

  constructor(scope: Construct, id: string, props: AlbProps) {
    /** Omitted */
  }

+ /**
+  * ALB listener
+  */
+ get listener(): IApplicationListener {
+    // NOTE: Since only one listener is created in the constructor, retrieve the first element of the array
+    //       Since there is no variable in public variables that allows calling the `addListener` method, cases with more than one element are not considered
+    return this.resource.listeners[0];
+ }
}

2.4.3. Instantiating the Created Construct Class in the Stack

Instantiate the Construct in the Stack as follows:

lib/sample-node-app-stack.ts
import type { StackProps } from "aws-cdk-lib";
import { Stack } from "aws-cdk-lib";
import type { Construct } from "constructs";

import { Alb } from "./constructs/alb";
import { Ecr } from "./constructs/ecr";
import { Vpc } from "./construct/vpc";

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

    // ECR
    const ecr = new Ecr(this, "Ecr");

    // VPC
    const vpc = new Vpc(this, "Vpc");

    // ALB
    const alb = new Alb(this, "Alb", {
      vpc: vpc.resource,
    });
  }
}

2.5. Creating the RDS

With the construction so far, it is now possible to access AWS resources within the VPC from the internet.
I want to build ECS next, but this application requires a database connection, and a process to establish a connection with the DB is executed when the application starts.
If the DB is not up at that time, an error will occur, so I will build the RDS before the ECS.

The procedure for building the RDS is as follows:

  1. Define the Construct
  2. Generate the password
  3. Create the instance
  4. Retrieve the secrets

2.5.1. Defining the Construct

First, define the Construct for RDS as follows:

lib/construct/rds.ts
import { Construct } from "constructs";

export class Rds extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);
  }
}

2.5.2. Generating the Password

I want to generate a password, but hard-coding it into the CDK source code is not ideal for security, so I will adopt a policy of saving it in Secrets Manager.
To achieve this, I will use the fromGeneratedSecret method of the Credentials class as follows:

lib/construct/rds.ts
+ import { Credentials } from "aws-cdk-lib/aws-rds";

+ interface RdsProps {
+   /**
+    * Username
+    * - Specify in the format of <your_name> (snake_case)
+    * @example "taro_yamada"
+    */
+   readonly username: string;
+ }

export class Rds extends Construct {
-  constructor(scope: Construct, id: string) {
+  constructor(scope: Construct, id: string, props: RdsProps) {
    super(scope, id);

+   // NOTE: Automatically generate password and save to Secrets Manager
+   const credentials = Credentials.fromGeneratedSecret(props.username);
  }
}

2.5.3. Creating the Instance

Next, I will implement the instance.
Since this is for practice (learning), I want low cost rather than high performance. Therefore, I chose MySQL without Aurora and selected the MICRO instance size.

Also, similar to the ALB, I will expose a connectableInstance of type IConnectable as a public variable to connect with the ECS.

lib/construct/rds.ts
+ import { InstanceClass, InstanceSize, InstanceType, type SecurityGroup, type SubnetSelection, type Vpc } from "aws-cdk-lib/aws-ec2";
+ import { Credentials, DatabaseInstance, DatabaseInstanceEngine, NetworkType, PostgresEngineVersion } from "aws-cdk-lib/aws-rds";
- import { Credentials } from "aws-cdk-lib/aws-rds";

interface RdsProps {
+ /**
+  * VPC where RDS will be created
+  */
+ readonly vpc: IVpc;
+ /**
+  * Database name
+  * - Specify in the format of <database_name> (snake_case)
+  * @example "sample_database"
+  */
+ readonly databaseName: string;
  /**
   * Username
   * - Specify in the format of <your_name> (snake_case)
   * @example "taro_yamada"
   */
  readonly username: string;
}

export class Rds extends Construct {
+ /**
+  * Connectable RDS instance
+  * - When connecting a resource to the RDS, use this instance as follows:
+  * ```typescript
+  * // Specify the resource you want to connect in the argument of `allowDefaultPortFrom`
+  * connectableInstance.connections.allowDefaultPortFrom(ecsService);
+  * ```
+  */
+ public readonly connectableInstance: IConnectable;

  constructor(scope: Construct, id: string, props: RdsProps) {
    super(scope, id);
    /** Omitted */
    // NOTE: Automatically generate password and save to Secrets Manager
    const credentials = Credentials.fromGeneratedSecret(props.username);

+   // NOTE: Create the instance
+   const instance = new DatabaseInstance(this, "MysqlInstance", {
+     engine: DatabaseInstanceEngine.mysql({
+       version: MysqlEngineVersion.VER_8_0,
+     }),
+     instanceType: InstanceType.of(
+       InstanceClass.T4G,
+       InstanceSize.MICRO,
+     ),
+     databaseName: props.databaseName,
+     vpc: props.vpc,
+     vpcSubnets: props.vpc.selectSubnets({
+       subnetType: SubnetType.PRIVATE_ISOLATED,
+     }),
+     networkType: NetworkType.IPV4,
+     availabilityZone: "ap-northeast-1a",
+     credentials,
+     removalPolicy: RemovalPolicy.DESTROY,
+   });

+   this.connectableInstance = instance;
  }
}

2.5.4. Retrieving the Secrets

Next, I will expose a variable named secrets as a public variable to specify the RDS secret information stored in Secrets Manager for the ECS task.
(This allows access to the RDS secret information through this variable.)

The implementation is as follows:

lib/construct/rds.ts
+ import { Secret } from "aws-cdk-lib/aws-secretsmanager";

export class Rds extends Construct {
+ /**
+  * Secret information for connecting to the database
+  *
+  * * Note: Secrets can be specified in the ECS container's `secrets` property without modification
+  * ```typescript
+  * // Example code for adding a container to an ECS task definition
+  * taskDefinition.addContainer("EcsContainer", {
+  *   secrets: rds.secrets,
+  * });
+  * ```
+  */
+ public readonly secrets: { [key: string]: Secret };

  constructor(scope: Construct, id: string, props: RdsProps) {
    // Omitted

+ // NOTE: Since IConnectable doesn't have a `secret` property, use the constant `instance` instead of `this` to retrieve the secret
+   const secret = instance.secret;
+   if (!secret) throw new Error("Could not retrieve RDS secret.");

+   this.secrets = this.getDatabaseSecrets(secret);
  }

+ /**
+  * Retrieve RDS secret information
+  */
+ private getDatabaseSecrets(secret: ISecret): { [key: string]: Secret } {
+   return {
+     DATABASE_ENGINE: Secret.fromSecretsManager(secret, "engine"),
+     DATABASE_USERNAME: Secret.fromSecretsManager(secret, "username"),
+     DATABASE_PASSWORD: Secret.fromSecretsManager(secret, "password"),
+     DATABASE_HOST: Secret.fromSecretsManager(secret, "host"),
+     DATABASE_PORT: Secret.fromSecretsManager(secret, "port"),
+     DATABASE_NAME: Secret.fromSecretsManager(secret, "dbname"),
+   };
+ }
}

2.5.5. Instantiating the Created Construct Class in the Stack

Instantiate the Construct in the Stack as follows:

lib/sample-node-app-stack.ts
+ import { Rds } from "./construct/rds";

export class SampleNodeAppStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps, readonly resourceName = "sample-node-app") {
    super(scope, id, props);

    /** Omitted */

    // ALB
    const alb = new Alb(this, "Alb", {
      vpc: vpc.value,
      resourceName,
      securityGroup: albSecurityGroup,
      subnets: vpc.getPublicSubnets(),
    });

+   // RDS
+   new Rds(this, "Rds", {
+     vpc: vpc.value,
+     databaseName: "sample_database",
+     username: "ren_yamanashi",
+   });
  }
}

2.6. Creating ECS

Now that the RDS has been built and we are ready to retrieve secrets from Secrets Manager, we will proceed to create the ECS.
The procedure for building the ECS is as follows:

  1. Create ECS cluster and task definition
  2. Add ECR container to the task definition
  3. Create ECS service
  4. Add ECS to the ALB target group

2.6.1. Creating ECS Cluster and Task Definition

We will define the ECS Construct and create the cluster and task definition as shown in the following code.

lib/construct/ecs.ts
import { Construct } from "constructs";
import { Cluster, CpuArchitecture, FargateTaskDefinition } from "aws-cdk-lib/aws-ecs";
import type { IVpc } from "aws-cdk-lib/aws-ec2";

interface EcsProps {
  /**
   * VPC where ECS will be created
   */
  readonly vpc: IVpc;
}

export class Ecs extends Construct {
  constructor(scope: Construct, id: string, props: EcsProps) {
    super(scope, id);

    // NOTE: Create the cluster
    const cluster = new Cluster(this, "EcsCluster", {
      vpc: props.vpc,
    });

    // NOTE: Create the task definition
    const taskDefinition = new FargateTaskDefinition(this, "EcsTaskDefinition", {
      cpu: 256,
      memoryLimitMiB: 512,
      runtimePlatform: {
        cpuArchitecture: CpuArchitecture.ARM64,
      },
    });
  }
}

2.6.2. Adding ECR Container to the Task Definition

Next, we will add the ECR container to the task definition.
We will also use the AwsLogDriver class to ensure that ECS log information is sent to CloudWatch Logs.
Since we are not operating in a production environment this time, we will set the log retention period to a short duration of one day.

lib/construct/ecs.ts
+ import { AwsLogDriver, Cluster, ContainerImage, CpuArchitecture, FargateTaskDefinition } from "aws-cdk-lib/aws-ecs";
+ import { RetentionDays } from "aws-cdk-lib/aws-logs";
+ import type { IRepository } from "aws-cdk-lib/aws-ecr";
- import { Cluster, CpuArchitecture, FargateTaskDefinition } from "aws-cdk-lib/aws-ecs";

interface EcsProps {
  /**
   * VPC where ECS will be created
   */
  readonly vpc: IVpc;
+ /**
+  * ECR Repository
+  */
+ readonly repository: IRepository;
+ /**
+  * Resources to connect with ECS
+  */
+ readonly connections: { alb: IConnectable; rds: IConnectable };
+ /**
+  * Secrets to pass to the container
+  */
+ readonly secrets: { [key: string]: Secret };
}

export class Ecs extends Construct {
  constructor(scope: Construct, id: string, props: EcsProps) {
    super(scope, id);

    /** Omitted */

+   // NOTE: Create log group
+   const logGroup = new LogGroup(this, "LogGroup", {
+     logGroupName: "/ecs/sample-node-app",
+     removalPolicy: RemovalPolicy.DESTROY,
+     retention: RetentionDays.ONE_DAY,
+   });
+   const logDriver = new AwsLogDriver({
+     logGroup,
+     streamPrefix: "container",
+   });

    // NOTE: Create the task definition
    const taskDefinition = new FargateTaskDefinition(this, "EcsTaskDefinition", {
      /** Omitted */
    });
+   taskDefinition.addContainer("Container", {
+     image: ContainerImage.fromEcrRepository(props.ecrRepository),
+     portMappings: [{ containerPort: 80, hostPort: 80 }],
+     secrets: props.secrets,
+     logging: logDriver,
+   });
  }
}

2.6.3. Creating the ECS Service

Now that the ECS cluster and task definition have been created and the container has been added, we will proceed to create the ECS service.
As shown in the architecture diagram above, we are configuring ECS with multi-AZ, so the desired task count is set to 2.

Additionally, to connect the created ECS service with the ALB and RDS, we will implement the connection using IConnectable.

lib/construct/ecs.ts
+ import { AwsLogDriver, Cluster, ContainerImage, CpuArchitecture, FargateService, FargateTaskDefinition, TaskDefinitionRevision } from "aws-cdk-lib/aws-ecs";
- import { AwsLogDriver, Cluster, ContainerImage, CpuArchitecture, FargateTaskDefinition } from "aws-cdk-lib/aws-ecs";
+ import type { SecurityGroup, SubnetSelection, Vpc } from "aws-cdk-lib/aws-ec2";
- import type { Vpc } from "aws-cdk-lib/aws-ec2";

interface EcsProps {
  /**
   * VPC where ECS will be created
   */
  readonly vpc: IVpc;
  /**
   * ECR repository
   */
  readonly repository: IRepository;
  /**
   * Resources to connect with ECS
   */
  readonly connections: { alb: IConnectable; rds: IConnectable };
  /**
   * Secrets to pass to the container
   */
  readonly secrets: { [key: string]: Secret };
}

export class Ecs extends Construct {
+ /**
+  * Resource to be specified as a target for the load balancer
+  */
+ public readonly loadBalancerTarget: IEcsLoadBalancerTarget;

  constructor(scope: Construct, id: string, props: EcsProps) {
    super(scope, id);

    /** Omitted */

    // NOTE: Create task definition
    /** Omitted */
    taskDefinition.addContainer("EcsContainer", {
      /** Omitted */
    });

+   // NOTE: Create service with Fargate launch type
+   this.fargateService = new FargateService(this, "EcsFargateService", {
+     cluster,
+     taskDefinition,
+     desiredCount: 2,
+     securityGroups: [props.securityGroup],
+     vpcSubnets: props.vpc.selectSubnets({
+       subnetType: SubnetType.PRIVATE_ISOLATED,
+     }),
+     taskDefinitionRevision: TaskDefinitionRevision.LATEST,
+   });

+   // NOTE: FargateService does not have a `default port`, so specify it explicitly
+   fargateService.connections.allowFrom(props.connections.alb, Port.tcp(80)); // Use IConnectable to connect ECS and ALB
+   props.connections.rds.connections.allowDefaultPortFrom(fargateService); // Use IConnectable to connect ECS and RDS

2.6.4. Adding ECS to the ALB Target Group

Finally, instantiate the ECS Construct in the Stack and register it as a target for the ALB.

lib/sample-node-app-stack.ts
+ import { Ecs } from "./construct/ecs";
+ import { Duration, Stack } from "aws-cdk-lib";
- import { Stack } from "aws-cdk-lib";

export class SampleNodeAppStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps, readonly resourceName = "sample-node-app") {
    super(scope, id, props);

    /** Omitted */

+   const ecs = new Ecs(this, "Ecs", {
+     vpc: vpc.value,
+     repository: ecr.repository,
+     ecrRepository: repository,
+     connections: {
+       alb: alb.connectableInstance,
+       rds: rds.connectableInstance,
+     },
+     secrets: rds.secrets,
+   });

+   // NOTE: Add task to target group
+   alb.addTargets("Ecs", {
+     port: 80,
+     targets: [ecs.fargateService],
+     healthCheck: {
+       path: "/",
+       interval: Duration.minutes(1),
+     },
+   });
  }
}

Up to this point, we have built the environment according to the initial architecture diagram.
After deploying, I want to verify the operation by actually sending requests to the ALB, so I'll implement it to output the ALB's domain name.

lib/sample-node-app-stack.ts
+ import { CfnOutput, Duration, Stack } from "aws-cdk-lib";
- import { Duration, Stack } from "aws-cdk-lib";

export class SampleNodeAppStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps, readonly resourceName = "sample-node-app") {
    super(scope, id, props);

    /** Omitted */

    // NOTE: Add task to target group
    alb.addTargets("Ecs", {
      /** Omitted */
    });

+   // NOTE: Output the ALB domain name
+   new CfnOutput(this, "LoadBalancerDomainName", {
+     value: alb.value.loadBalancerDnsName,
+   });
  }
}

cdk deploy

Once the deployment is complete, the ALB domain name will be output, so let's try sending a request to it.

# Send GET request to `/` 
curl http://<ALB domain name>
Hello World
# Send POST request to `/posts` 
curl -X POST http://<ALB domain name>/posts -H "Content-Type: application/json" -d '{"title": "sample post"}'
{"id":"4bc54a3f-9c9d-4662-9d45-856baf434ea2","title":"sample post"}
# Send GET request to `/posts` 
curl http://<ALB domain name>/posts
{"id":"4bc54a3f-9c9d-4662-9d45-856baf434ea2","title":"sample post"}

Success, the response came back!

3. Summary

In this article, we built an ECS (Fargate) and RDS environment in a multi-AZ configuration using AWS CDK. This was my first time working with CDK, and it was a great development experience as I could build it while understanding how each resource connects. In the future, I want to explore other AWS resources and try things like IPv6 configurations.

3.1. Artifacts

The final source code for this project is as follows:
https://github.com/ren-yamanashi/ecs-fargate-cdk

3.2. References

I referred to the following sites!

GitHubで編集を提案

Discussion