CDK patterns for serverless container with AWS Fargate

Overview

NPM version PyPI version Release

cdk-fargate-patterns

CDK patterns for serverless container with AWS Fargate

DualAlbFargateService

Inspired by Vijay Menon from the AWS blog post introduced in 2019, DualAlbFargateService allows you to create one or many fargate services with both internet-facing ALB and internal ALB associated with all services. With this pattern, fargate services will be allowed to intercommunicat via internal ALB while external inbound traffic will be spread across the same service tasks through internet-facing ALB.

The sample below will create 3 fargate services associated with both external and internal ALBs. The internal ALB will have an alias(internal.svc.local) auto-configured from Route 53 so services can communite through the private ALB endpoint.

new DualAlbFargateService(stack, 'Service', {
  spot: true, // FARGATE_SPOT only cluster
  tasks: [
    {
      listenerPort: 80,
      task: orderTask,
      desiredCount: 2,
      // customize the service autoscaling policy
      scalingPolicy: {
        maxCapacity: 20,
        requestPerTarget: 1000,
        targetCpuUtilization: 50,
      },
    },
    { listenerPort: 8080, task: customerTask, desiredCount: 2 },
    { listenerPort: 9090, task: productTask, desiredCount: 2 },
  ],
  route53Ops: {
    zoneName, // svc.local
    externalAlbRecordName, // external.svc.local
    internalAlbRecordName, // internal.svc.local
  },
});

Fargate Spot Support

By enabling the spot property, 100% fargate spot tasks will be provisioned to help you save up to 70%. Check more details about Fargate Spot. This is a handy catch-all flag to force all tasks to be FARGATE_SPOT only.

To specify mixed strategy with partial FARGATE and partial FARGATE_SPOT, specify the capacityProviderStrategy for individual tasks like

new DualAlbFargateService(stack, 'Service', {
  tasks: [
    {
      listenerPort: 8080,
      task: customerTask,
      desiredCount: 2,
      capacityProviderStrategy: [
        {
          capacityProvider: 'FARGATE',
          base: 1,
          weight: 1,
        },
        {
          capacityProvider: 'FARGATE_SPOT',
          base: 0,
          weight: 3,
        },
      ],
    },
  ],
});

The custom capacity provider strategy will be applied if capacityProviderStretegy is specified, otherwise, 100% spot will be used when spot: true. The default policy is 100% Fargate on-demand.

ECS Exec

Simply turn on the enableExecuteCommand property to enable the ECS Exec support for all services.

Internal or External Only

By default, all task(s) defined in the DualAlbFargateService will be registered to both external and internal ALBs. Set accessibility to make it internal only, external only, or both.

new DualAlbFargateService(stack, 'Service', {
    tasks: [
      // this task is internal only
      { listenerPort: 8080, task: task1, accessibility: LoadBalancerAccessibility.INTERNAL_ONLY},
      // this task is external only
      { listenerPort: 8081, task: task2, accessibility: LoadBalancerAccessibility.EXTERNAL_ONLY},
      // this task is both external and internal facing(default behavior)
      { listenerPort: 8082, task: task3 },
    ],
  });

Please note if all tasks are defined as INTERNAL_ONLY, no external ALB will be created. Similarly, no internal ALB will be created if all defined as EXTERNAL_ONLY.

VPC Subnets

By default, all tasks will be deployed in the private subnets. You will need the NAT gateway for the default route associated with the private subnets to ensure the task can successfully pull the container images.

However, you are allowed to specify vpcSubnets to customize the subnet selection.

To deploy all tasks in public subnets, one per AZ:

new DualAlbFargateService(stack, 'Service', {
    vpcSubnets: {
      subnetType: ec2.SubnetType.PUBLIC,
      onePerAz: true,
  },
  ...
});

This will implicitly enable the auto assign public IP for each fargate task so the task can successfully pull the container images from external registry. However, the ingress traffic will still be balanced via the external ALB.

To deploy all tasks in specific subnets:

new DualAlbFargateService(stack, 'Service', {
  vpcSubnets: { 
      subnets: [
        ec2.Subnet.fromSubnetId(stack, 'sub-1a', 'subnet-0e9460dbcfc4cf6ee'),
        ec2.Subnet.fromSubnetId(stack, 'sub-1b', 'subnet-0562f666bdf5c29af'),
        ec2.Subnet.fromSubnetId(stack, 'sub-1c', 'subnet-00ab15c0022872f06'),
      ],
    },
  ...
});

Sample Application

This repository comes with a sample applicaiton with 3 services in Golang. On deployment, the Order service will be exposed externally on external ALB port 80 and all requests to the Order service will trigger sub-requests internally to another other two services(product and customer) through the internal ALB and eventually aggregate the response back to the client.

Deploy

To deploy the sample application in you default VPC:

// install first
$ yarn install
// compile the ts to js
$ yarn build
$ npx cdk --app lib/integ.default.js -c use_default_vpc=1 diff
$ npx cdk --app lib/integ.default.js -c use_default_vpc=1 deploy

On deployment complete, you will see the external ALB endpoint in the CDK output. cURL the external HTTP endpoint and you should be able to see the aggregated response.

$ curl http://demo-Servi-EH1OINYDWDU9-1397122594.ap-northeast-1.elb.amazonaws.com

{"service":"order", "version":"1.0"}
{"service":"product","version":"1.0"}
{"service":"customer","version":"1.0"}

WordPress

Use the WordPress construct to create a serverless WordPress service with AWS Fargate, Amazon EFS filesystem and Aurora serverless database. All credentials auto generated from the AWS Secret Manager and securely inject the credentials into the serverless container with the auto generated IAM task execution role.

new WordPress(stack, 'WP', {
  auroraServerless: true,
  spot: true,
  enableExecuteCommand: true,
});
You might also like...
λ Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda.
λ Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda.

λ Swoole Runtime for AWS Lambda Run PHP Coroutines & Fibers as-a-Service on the AWS Lambda. Getting started Create your Lambda function index.php ?ph

WHMCS Automation Module For AWS EC2 Instances.
WHMCS Automation Module For AWS EC2 Instances.

使用方法 把AWSEC2目录直接扔到 WHMCS/modules/servers 下即可 自定义字段 cloudinit (文本框 textarea 在订单页面显示) pem (文本框 textarea 仅管理员可见) data (文本框 textarea 仅管理员可见) 特性 动态IP (关机再开

AWS DynamoDB session handler for Magento (experimental!)

Magento Session Handler for AWS DynamoDB Author: Fabrizio Branca TODO: disable automatic gc create cron that does gc how does it keep track of lifetim

This demo app shows you how to run a simple PHP application on AWS Elastic Beanstalk.

Elastic Beanstalk + PHP Demo App - "Share Your Thoughts" This demo app shows you how to run a simple PHP application on AWS Elastic Beanstalk. Run the

A Laravel artisan based package to create the AWS (SES + SNS) infrastructure to receive email event notifications with Http/Https endpoint.
A Laravel artisan based package to create the AWS (SES + SNS) infrastructure to receive email event notifications with Http/Https endpoint.

Laravel SES Tracking Setup the AWS infrastructure to handle email events using SES/SNS and http/s endpoints with a single Laravel artisan command. Thi

PHP Runtime Layer for AWS Lambda

PHP Layer For AWS Lambda Ever wanted to run PHP websites in AWS Lambda? It's your lucky day! This Lambda Runtime Layer runs the PHP 7.3/7.1 webserver

This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized objects in DynamoDB 🚀.

DynamoDB Storable This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized

A tool to create php lambda's in AWS via custom runtime api

Getting Started This composer library assists in the creation, configuration, and testing of an AWS Lambda function. It utilizes the AWS Lambda custom

Simple, single-file and dependency-free AWS S3 client.

Simple, single-file and dependency-free AWS S3 client. Why? In some scenarios we want the simplest and lightest S3 client possible. For example in Bre

Releases(v0.3.73)
Owner
Pahud Hsieh
Repositories under my account are personal projects and not supported by AWS.
Pahud Hsieh
Lumen on Docker - Skeleton project with Nginx, MySQL & PHP 8 | Aws ECS, Google Kubernates, Azure Container Engine

Docker infrastructure for Lumen Description Microservice Lumen is a starting skeleton based on Docker and Lumen Framework. This project helps to devel

Fabrizio Cafolla 218 Sep 25, 2022
Apache OpenWhisk is an open source serverless cloud platform

OpenWhisk OpenWhisk is a serverless functions platform for building cloud applications. OpenWhisk offers a rich programming model for creating serverl

The Apache Software Foundation 5.9k Jan 8, 2023
Demo serverless applications, examples code snippets and resources for PHP

The Serverless LAMP stack Examples Code example Description AWS blog link 0.1-SimplePhpFunction A very simple implementation of a PHP Lambda function.

AWS Samples 303 Dec 20, 2022
The easiest way to match data structures like JSON/PlainText/XML against readable patterns. Sandbox:

PHP Matcher Library created for testing all kinds of JSON/XML/TXT/Scalar values against patterns. API: PHPMatcher::match($value = '{"foo": "bar"}', $p

Coduo 774 Dec 31, 2022
Repo do vídeo do youtube de Design Patterns - Decorator

DesignPatternsPHP-Decorator Repo do vídeo do Youtube de Design Patterns - Decorator Link do vídeo Decorator em PHP 8 Imagem de exemplo Link do cadastr

Leonardo Tumadjian 10 Aug 18, 2022
Learning design patterns by implementing them in various programming languages.

design-patterns Learning design patterns by implementing them in various programming languages. Creational design patterns Creational design patterns

Paweł Tryfon 1 Dec 13, 2021
Sample code for several design patterns in PHP 8

DesignPatternsPHP Read the Docs of DesignPatternsPHP or Download as PDF/Epub This is a collection of known design patterns and some sample codes on ho

null 21k Jan 5, 2023
Detection of design patterns in PHP code

Pattern Detector for PHP Detects design pattern in your code

Jean-François Lépine 105 Aug 23, 2022
PHP Library that implements several messaging patterns for RabbitMQ

Thumper Thumper is a PHP library that aims to abstract several messaging patterns that can be implemented over RabbitMQ. Inside the examples folder yo

php-amqplib 276 Nov 20, 2022
Examples of some common design patterns implemented in php

What is a Design Pattern? Design patterns are typical solutions to common problems in software design. Each pattern is like a blueprint that you can c

Bakhtiyor Bahritidinov 4 Feb 11, 2022