Serverless public facing API hosted on AWS Fargate

Nathan Peck profile picture
Nathan Peck
Senior Developer Advocate at AWS


Sometimes you want to create a public facing service, but you want stricter control over the networking of the service. This pattern is especially useful for the following usecases:

  • An API which is public facing but needs an extra layer of security hardening by not even having a public IP address that an attacker could send a request directly to.
  • An API service which needs to be massively horizontally scalable while not being constrained by number of IP addresses available.
  • A web or API service which initiates outbound connections but to the public you want those connections to originate from a specific and limited set of IP addresses that can be whitelisted.


This pattern is not suited for:

Services that have high throughput/bandwidth to other services on the internet. Because this pattern use a NAT gateway to provide internet to resources in a private subnet you will be sending a lot of bandwidth through the NAT gateway and paying extra per GB of outbound traffic. Instead consider using the public facing version of this pattern, which hosts public facing tasks with public IP addresses assigned by AWS Fargate


At a high level the architecture looks like this:

Public subnetPublic subnetVPCAvailability Zone 1Availability Zone 2Private subnetPrivate subnetInternet gatewayApplicationLoad BalancerLoad Balancer has nodes in each AZTrafficENIPort 80ENIPort 80ENIPort 80Port 80AWS FargateContainerPort 80ContainerPort 80ContainerPort 80

Everything is deployed in an Amazon Virtual Private Cloud (VPC) which has two subnets:

  • Public subnet: Has an attached internet gateway to allow resources launched in that subnet to accept connections from the internet, and initiate connections to the internet. Resources in this subnet have public IP addresses.
  • Private subnet: For internal resources. AWS Fargate tasks in this subnet have no direct internet access, and only have private IP addresses that are internal to the VPC, not directly accessible by the public.

The public facing subnet hosts a couple resources:

  • Public facing load balancer: Accepts inbound connections on specific ports, and forwards acceptable traffic to resources inside the private subnet.
  • NAT gateway: A networking bridge to allow resources inside the private subnet to initiate outbound communications to the internet, while not allowing inbound connections.


Application Load Balancer has a constant hourly charge, which gives it a baseline cost, even if your application receives no traffic.

If you expect your API to receive very low traffic, or intermittent traffic, then you may prefer to use the API Gateway pattern for AWS Fargate. Amazon API Gateway charges per request, with no minimum fee. However, this can add up to a higher per request cost if you do receive large amounts of traffic.


This pattern requires that you have an AWS account, and that you use AWS Serverless Application Model (SAM) CLI. If not already installed then please install SAM CLI for your system.

Define the VPC

To deploy this pattern you will use the base pattern that defines a large VPC for an Amazon ECS cluster. This will deploy the public and private subnets as well as the NAT gateway that provides internet access to the private subnets. Download the vpc.yml file from that pattern, but don't deploy it yet. You will deploy the VPC later as part of this pattern.

Define the cluster

The following AWS CloudFormation template creates a simple Amazon ECS cluster that is setup for serverless usage with AWS Fargate.

File: cluster.ymlLanguage: yml
AWSTemplateFormatVersion: '2010-09-09'
Description: Empty ECS cluster that has no EC2 instances. It is designed
             to be used with AWS Fargate serverless capacity

  # Cluster that keeps track of container deployments
    Type: AWS::ECS::Cluster
        - Name: containerInsights
          Value: enabled

  # This is a role which is used within Fargate to allow the Fargate agent
  # to download images, and upload logs.
    Type: AWS::IAM::Role
          - Effect: Allow
              Service: []
            Action: ['sts:AssumeRole']
                aws:SourceArn: !Sub arn:aws:ecs:${AWS::Region}:${AWS::AccountId}:*
                aws:SourceAccount: !Ref AWS::AccountId
      Path: /

      # This role enables basic features of ECS. See reference:
        - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

    Description: The ECS cluster into which to launch resources
    Value: !Ref ECSCluster
    Description: The role used to start up a task
    Value: !Ref ECSTaskExecutionRole

Define the service

Next we need to define an Amazon ECS service that deploys a container using AWS Fargate. The following template deploys an Application Load Balancer into the VPC public subnet, while deploying the containers themselves into AWS Fargate in the private subnet:

File: service.ymlLanguage: yml
AWSTemplateFormatVersion: '2010-09-09'
Description: An example service that deploys in AWS VPC networking mode
             on AWS Fargate. Service runs with networking in private subnets
             and with private IP addresses only.

    Type: String
    Description: The VPC that the service is running inside of
    Type: List<AWS::EC2::Subnet::Id>
    Description: List of public subnet ID's to put the load balancer in
    Type: List<AWS::EC2::Subnet::Id>
    Description: List of private subnet ID's to put the tasks in
    Type: String
    Description: The name of the ECS cluster into which to launch capacity.
    Type: String
    Description: The role used to start up an ECS task
    Type: String
    Default: web
    Description: A name for the service
    Type: String
    Description: The url of a docker image that contains the application process that
                 will handle the traffic for this service
    Type: Number
    Default: 256
    Description: How much CPU to give the container. 1024 is 1 CPU
    Type: Number
    Default: 512
    Description: How much memory in megabytes to give the container
    Type: Number
    Default: 80
    Description: What port that the application expects traffic on
    Type: Number
    Default: 2
    Description: How many copies of the service task to run


  # The task definition. This is a simple metadata description of what
  # container to run, and what resource requirements it has.
    Type: AWS::ECS::TaskDefinition
      Family: !Ref ServiceName
      Cpu: !Ref ContainerCpu
      Memory: !Ref ContainerMemory
      NetworkMode: awsvpc
        - FARGATE
      ExecutionRoleArn: !Ref ECSTaskExecutionRole
        - Name: !Ref ServiceName
          Cpu: !Ref ContainerCpu
          Memory: !Ref ContainerMemory
          Image: !Ref ImageUrl
            - ContainerPort: !Ref ContainerPort
              HostPort: !Ref ContainerPort
            LogDriver: 'awslogs'
              mode: non-blocking
              max-buffer-size: 25m
              awslogs-group: !Ref LogGroup
              awslogs-region: !Ref AWS::Region
              awslogs-stream-prefix: !Ref ServiceName

  # The service. The service is a resource which allows you to run multiple
  # copies of a type of task, and gather up their logs and metrics, as well
  # as monitor the number of running tasks and replace any that have crashed
    Type: AWS::ECS::Service
    # Avoid race condition between ECS service creation and associating
    # the target group with the LB
    DependsOn: PublicLoadBalancerListener
      ServiceName: !Ref ServiceName
      Cluster: !Ref ClusterName
      LaunchType: FARGATE
          AssignPublicIp: DISABLED
            - !Ref ServiceSecurityGroup
          Subnets: !Ref PrivateSubnetIds
        MaximumPercent: 200
        MinimumHealthyPercent: 75
      DesiredCount: !Ref DesiredCount
      TaskDefinition: !Ref TaskDefinition
        - ContainerName: !Ref ServiceName
          ContainerPort: !Ref ContainerPort
          TargetGroupArn: !Ref ServiceTargetGroup

  # Security group that limits network access
  # to the task
    Type: AWS::EC2::SecurityGroup
      GroupDescription: Security group for service
      VpcId: !Ref VpcId

  # Keeps track of the list of tasks for the service
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
      HealthCheckIntervalSeconds: 6
      HealthCheckPath: /
      HealthCheckProtocol: HTTP
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 2
      TargetType: ip
      Port: !Ref ContainerPort
      Protocol: HTTP
      UnhealthyThresholdCount: 10
      VpcId: !Ref VpcId
        - Key: deregistration_delay.timeout_seconds
          Value: 0

  # A public facing load balancer, this is used as ingress for
  # public facing internet traffic.
    Type: AWS::EC2::SecurityGroup
      GroupDescription: Access to the public facing load balancer
      VpcId: !Ref VpcId
        # Allow access to public facing ALB from any IP address
        - CidrIp:
          IpProtocol: -1
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
      Scheme: internet-facing
      - Key: idle_timeout.timeout_seconds
        Value: '30'
      Subnets: !Ref PublicSubnetIds
        - !Ref PublicLoadBalancerSG
    Type: AWS::ElasticLoadBalancingV2::Listener
        - Type: 'forward'
              - TargetGroupArn: !Ref ServiceTargetGroup
                Weight: 100
      LoadBalancerArn: !Ref 'PublicLoadBalancer'
      Port: 80
      Protocol: HTTP

  # Open up the service's security group to traffic originating
  # from the security group of the load balancer.
    Type: AWS::EC2::SecurityGroupIngress
      Description: Ingress from the public ALB
      GroupId: !Ref ServiceSecurityGroup
      IpProtocol: -1
      SourceSecurityGroupId: !Ref 'PublicLoadBalancerSG'

  # This log group stores the stdout logs from this service's containers
    Type: AWS::Logs::LogGroup

Deploy it all

You should now have the following three files:

  • vpc.yml - Template for the base VPC that you wish to host resources in
  • cluster.yml - Template for the ECS cluster and its capacity provider
  • service.yml - Template for the web service that will be deployed on the cluster

Use the following parent stack to deploy all three stacks:

File: parent.ymlLanguage: yml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Parent stack that deploys VPC, Amazon ECS cluster for AWS Fargate,
             and a serverless Amazon ECS service deployment that hosts
             the task containers on AWS Fargate


  # The networking configuration. This creates an isolated
  # network specific to this particular environment
    Type: AWS::Serverless::Application
      Location: vpc.yml

  # This stack contains the Amazon ECS cluster itself
    Type: AWS::Serverless::Application
      Location: cluster.yml

  # This stack contains the container deployment
    Type: AWS::Serverless::Application
      Location: service.yml
        VpcId: !GetAtt VpcStack.Outputs.VpcId
        PublicSubnetIds: !GetAtt VpcStack.Outputs.PublicSubnetIds
        PrivateSubnetIds: !GetAtt VpcStack.Outputs.PrivateSubnetIds
        ClusterName: !GetAtt ClusterStack.Outputs.ClusterName
        ECSTaskExecutionRole: !GetAtt ClusterStack.Outputs.ECSTaskExecutionRole

Use the following command to deploy all three stacks:

Language: shell
sam deploy \
  --template-file parent.yml \
  --stack-name serverless-api-environment \
  --resolve-s3 \
  --capabilities CAPABILITY_IAM

Test it out

Open the Amazon ECS cluster in the web console and verify that the service has been created with a desired count of two. You will observe the service create tasks that launch into AWS Fargate. Last but not least ECS will register the task's IP addresses with the Application Load Balancer so that it can send them traffic.

On the "Health & Metrics" tab of the service details page you can click on the load balancer name to navigate to the load balancer in the EC2 console. This will give you the load balancer's public facing CNAME that you can copy and paste into your browser to verify that the sample NGINX webserver is up and running.

Tear it down

You can tear down the entire stack with the following command:

Language: shell
sam delete --stack-name serverless-api-environment

See Also

Alternative Patterns

Not quite right for you? Try another way to do this:

Website  Serverless public facing website hosted on AWS Fargate

Want to deploy a more public facing website instead?

EC2 Instances  Public facing website hosted on EC2 instances

Host really large deployments on EC2 instances.