Skip to content

Instantly share code, notes, and snippets.

@nathanpeck
Created August 29, 2019 15:00
Show Gist options
  • Save nathanpeck/c488d39e944d3a75fd9a28a166d468a5 to your computer and use it in GitHub Desktop.
Save nathanpeck/c488d39e944d3a75fd9a28a166d468a5 to your computer and use it in GitHub Desktop.
An AWS CDK deployment to AWS Fargte, optimized for speed
import ec2 = require('@aws-cdk/aws-ec2');
import ecs = require('@aws-cdk/aws-ecs');
import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import cdk = require('@aws-cdk/core');
class PublicFargateService extends cdk.Stack {
constructor(scope: cdk.App, id: string) {
super(scope, id);
// Create VPC and Fargate Cluster
// NOTE: Limit AZs to avoid reaching resource quotas
const vpc = new ec2.Vpc(this, 'MyVpc', { maxAzs: 2 });
const cluster = new ecs.Cluster(this, 'Cluster', { vpc: vpc });
// Load balancer for the service
const LB = new elbv2.ApplicationLoadBalancer(this, 'LB', {
vpc:vpc,
internetFacing: true
});
const loadBalancerListener = LB.addListener('PublicListener', { port: 80, open: true });
loadBalancerListener.addTargetGroups('default', {
targetGroups: [new elbv2.ApplicationTargetGroup(this, 'default', {
vpc: vpc,
protocol: elbv2.ApplicationProtocol.HTTP,
port: 80
})]
});
// Output the DNS where you can access your service
new cdk.CfnOutput(this, 'LoadBalancerDNS', { value: LB.loadBalancerDnsName });
// Name service
const nameTaskDefinition = new ecs.FargateTaskDefinition(this, 'name-task-definition', {});
const nameContainer = nameTaskDefinition.addContainer('name', {
image: ecs.ContainerImage.fromAsset("../../example-apps/greeter/name"),
memoryLimitMiB: 512,
});
nameContainer.addPortMappings({
containerPort: 80
});
const nameService = new ecs.FargateService(this, 'name-service', {
cluster: cluster,
desiredCount: 2,
taskDefinition: nameTaskDefinition,
// Ensure that the rollout is able to happen in one round
maxHealthyPercent: 200,
minHealthyPercent: 100,
// No need for a public IP, we have NAT gateway in this VPC
assignPublicIp: false
});
loadBalancerListener.addTargets('name', {
port: 80,
pathPattern: '*',
priority: 1,
// Only 10 seconds for new tasks to become healthy.
// Increase if your application is slower to startup
healthCheck: {
healthyThresholdCount: 2,
interval: cdk.Duration.seconds(5),
timeout: cdk.Duration.seconds(2)
},
// Only drain containers for 10 seconds when stopping them.
// Increase if your app has long lived connections
deregistrationDelay: cdk.Duration.seconds(10),
targets: [nameService]
});
}
}
const app = new cdk.App();
new PublicFargateService(app, 'public-fargate-service');
app.synth();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment