Skip to content

Instantly share code, notes, and snippets.

@jessejohnson
Last active March 22, 2023 09:53
Show Gist options
  • Save jessejohnson/9689167b1b5555697c918304358075ae to your computer and use it in GitHub Desktop.
Save jessejohnson/9689167b1b5555697c918304358075ae to your computer and use it in GitHub Desktop.
Write cdk code to deploy ecs app with load balancer attached
using Amazon.CDK;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
namespace MyNamespace
{
public class MyStack : Stack
{
public MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
// Create a new VPC
var vpc = new Vpc(this, "MyVpc", new VpcProps
{
MaxAzs = 3
});
// Create a new ECS cluster
var cluster = new Cluster(this, "MyCluster", new ClusterProps
{
Vpc = vpc
});
// Create a new ECS task definition
var taskDefinition = new FargateTaskDefinition(this, "MyTaskDefinition");
// Add a container to the task definition
var container = taskDefinition.AddContainer("MyContainer", new ContainerDefinitionOptions
{
Image = ContainerImage.FromRegistry("nginx:latest"),
MemoryLimitMiB = 256
});
// Create a new ECS service
var service = new FargateService(this, "MyService", new FargateServiceProps
{
Cluster = cluster,
TaskDefinition = taskDefinition,
DesiredCount = 2,
ServiceName = "my-service"
});
// Create a new load balancer
var lb = new ApplicationLoadBalancer(this, "MyLoadBalancer", new ApplicationLoadBalancerProps
{
Vpc = vpc,
InternetFacing = true
});
// Create a new target group
var targetGroup = new ApplicationTargetGroup(this, "MyTargetGroup", new ApplicationTargetGroupProps
{
Vpc = vpc,
Port = 80,
TargetType = TargetType.IP,
Protocol = ApplicationProtocol.HTTP
});
// Add the ECS service as a target for the target group
targetGroup.AddTarget(service);
// Create a new listener for the load balancer
var listener = lb.AddListener("MyListener", new BaseApplicationListenerProps
{
Port = 80,
Open = true,
DefaultTargetGroups = new[] { targetGroup }
});
}
}
}
// This code will create an Amazon ECS app with an nginx container running on a Fargate task.
// The app will be deployed to an ECS cluster running in a VPC.
// The load balancer will be an Application Load Balancer that is attached to the VPC.
// The load balancer will forward requests to the ECS service using a target group,
// which is configured to route traffic to the IP addresses of the ECS tasks. Finally, the load balancer will...
from aws_cdk import (
core,
aws_ec2 as ec2,
aws_ecs as ecs,
aws_ecs_patterns as ecs_patterns,
aws_elasticloadbalancingv2 as elbv2
)
class ECSStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# create a VPC for the ECS cluster and load balancer
vpc = ec2.Vpc(self, "MyVPC", max_azs=2)
# create an ECS cluster
cluster = ecs.Cluster(self, "MyCluster", vpc=vpc)
# create a load balancer
lb = elbv2.ApplicationLoadBalancer(self, "MyLB", vpc=vpc, internet_facing=True)
# create a target group for the ECS service
target_group = elbv2.ApplicationTargetGroup(self, "MyTargetGroup", port=80, vpc=vpc, health_check={"path": "/health"})
# create an ECS task definition
task_definition = ecs.FargateTaskDefinition(self, "MyTaskDef")
# add a container to the task definition
container = task_definition.add_container("MyContainer", image=ecs.ContainerImage.from_registry("nginx"))
container.add_port_mappings(ecs.PortMapping(container_port=80))
# create an ECS service with the task definition and target group
service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "MyService", cluster=cluster, task_definition=task_definition, target_group=target_group)
# attach the load balancer to the target group
listener = lb.add_listener("MyListener", port=80)
listener.add_targets("MyTarget", port=80,
import * as cdk from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
const app = new cdk.App();
// Create a new VPC
const vpc = new ec2.Vpc(app, 'MyVpc', {
maxAzs: 3
});
// Create a new ECS cluster
const cluster = new ecs.Cluster(app, 'MyCluster', {
vpc: vpc
});
// Create a new ECS task definition
const taskDefinition = new ecs.FargateTaskDefinition(app, 'MyTaskDefinition');
// Add a container to the task definition
const container = taskDefinition.addContainer('MyContainer', {
image: ecs.ContainerImage.fromRegistry('nginx:latest'),
memoryLimitMiB: 256
});
// Create a new ECS service
const service = new ecs.FargateService(app, 'MyService', {
cluster: cluster,
taskDefinition: taskDefinition,
desiredCount: 2,
serviceName: 'my-service'
});
// Create a new load balancer
const lb = new elbv2.ApplicationLoadBalancer(app, 'MyLoadBalancer', {
vpc: vpc,
internetFacing: true
});
// Create a new target group
const targetGroup = new elbv2.ApplicationTargetGroup(app, 'MyTargetGroup', {
vpc: vpc,
port: 80,
targetType: elbv2.TargetType.IP,
protocol: elbv2.ApplicationProtocol.HTTP
});
// Add the ECS service as a target for the target group
targetGroup.addTarget(service);
// Create a new listener for the load balancer
const listener = lb.addListener('MyListener', {
port: 80,
open: true,
defaultTargetGroups: [targetGroup]
});
app.synth();
// This code will create an Amazon ECS app with an nginx container running on a Fargate task.
// The app will be deployed to an ECS cluster running in a VPC.
// The load balancer will be an Application Load Balancer that is attached to the VPC.
// The load balancer will forward requests to the ECS service using a target group,
// which is configured to route traffic to the IP addresses of the ECS tasks.
// Finally, the load balancer will listen on port 80 for incoming HTTP traffic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment