Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The Fargateway Pattern #182

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions the-fargateway/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# The Fargateway

This is an example CDK stack to run a Fargate service behind an API Gateway. It uses CloudMap for service discovery and does not need a Load Balancer. It's based on this blog post - https://aws.amazon.com/blogs/architecture/field-notes-serverless-container-based-apis-with-amazon-ecs-and-amazon-api-gateway/

![Architecture](img/arch.drawio.png)

## When You Would Use This Pattern

This patterns allows an Fargate service to leaverage the capabilities provided by API Gateway (e.g. import/export of OpenAPI defintions, throttling, authorization).

An advantage compared to [load balanced Fargate service](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-patterns-readme.html#application-load-balanced-services) are lower costs. In Api Gateway 1 million requests per month costs around $1 whereas an ALB costs around $16 per month.

## How to test pattern

After deployment you will have an api gateway where the nginx Fargate service is served.

## Available Versions

- [TypeScript](typescript/)
Binary file added the-fargateway/img/arch.drawio.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions the-fargateway/typescript/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
*.js
!jest.config.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out

# Parcel default cache directory
.parcel-cache
6 changes: 6 additions & 0 deletions the-fargateway/typescript/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
10 changes: 10 additions & 0 deletions the-fargateway/typescript/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# The Fargateway

## Useful commands

- `npm run build` compile typescript to js
- `npm run watch` watch for changes and compile
- `npm run test` perform the jest unit tests
- `npm run deploy` deploy this stack to your default AWS account/region
- `cdk diff` compare deployed stack with current state
- `cdk synth` emits the synthesized CloudFormation template
9 changes: 9 additions & 0 deletions the-fargateway/typescript/bin/the-fargateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { TheFargatewayStack } from '../lib/the-fargateway-stack';

const app = new cdk.App();
new TheFargatewayStack(app, 'TheFargatewayStack', {
env: { region: "eu-west-1" }
});
7 changes: 7 additions & 0 deletions the-fargateway/typescript/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"app": "npx ts-node bin/the-fargateway.ts",
"context": {
"@aws-cdk/core:enableStackNameDuplicates": "true",
"aws-cdk:enableDiffNoFail": "true"
}
}
7 changes: 7 additions & 0 deletions the-fargateway/typescript/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
};
73 changes: 73 additions & 0 deletions the-fargateway/typescript/lib/the-fargateway-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import * as apiv2 from '@aws-cdk/aws-apigatewayv2';
import * as apiv2int from '@aws-cdk/aws-apigatewayv2-integrations';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as ecs from '@aws-cdk/aws-ecs';
import * as servicediscovery from '@aws-cdk/aws-servicediscovery';
import * as cdk from '@aws-cdk/core';

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

// Fargate and CloudMap needs to be setup in a VPC
const vpc = new ec2.Vpc(this, 'Vpc', {
maxAzs: 2, // Default is all AZs in the region
});

// CloudMap Namespace
const namespace = new servicediscovery.PrivateDnsNamespace(this, 'Namespace', {
name: 'cdk.dev',
vpc,
});

// Fargate Service (a simple nginx container)
const taskDefinition = new ecs.TaskDefinition(this, 'taskdef', {
compatibility: ecs.Compatibility.FARGATE,
memoryMiB: '512',
cpu: '256',
});
const containerDef = taskDefinition.addContainer('nginx', {
image: ecs.RepositoryImage.fromRegistry('public.ecr.aws/nginx/nginx:latest'),
logging: ecs.LogDrivers.awsLogs({ streamPrefix: 'fargateway' }),
healthCheck: {
command: ['curl --fail http://localhost || exit 1'],
},
});
containerDef.addPortMappings({ containerPort: 80 });

const cluster = new ecs.Cluster(this, 'cluster', { vpc });
const fargateService = new ecs.FargateService(this, 'fargateway', {
taskDefinition,
cluster,
cloudMapOptions: {
cloudMapNamespace: namespace,
dnsRecordType: servicediscovery.DnsRecordType.SRV,
name: 'fargateway',
},
});

// Http Api Gateway with default integration (routes all traffic to the Fargate service)
const apiSecurityGroup = new ec2.SecurityGroup(this, 'api', { vpc });
const vpcLink = new apiv2.VpcLink(this, 'VpcLink', {
vpc,
securityGroups: [apiSecurityGroup],
});

const fargatePort = new ec2.Port({ protocol: ec2.Protocol.TCP, fromPort: 80, toPort: 80, stringRepresentation: 'API to Fargate' });
fargateService.connections.allowFrom(apiSecurityGroup, fargatePort);

const defaultIntegration = new apiv2int.HttpServiceDiscoveryIntegration({
vpcLink,
service: fargateService.cloudMapService!,
});

// Connect it to "api"
const api = new apiv2.HttpApi(this, 'fargateapi', {
defaultIntegration,
});

new cdk.CfnOutput(this, 'HTTP API Url', {
value: api.url ?? 'Something went wrong with the deploy'
});
}
}
Loading