ECS Fargate networking

Does your ECS Fargate app need a NAT gateway?

Your containers need images, logs, secrets and sometimes an external API. Follow those connections before deciding whether a NAT gateway or private endpoints make sense.

By Published 28 November 2026Updated 28 November 202612 minute read

A Fargate task does not always need a NAT gateway. It needs a working route to every service it uses.

Private endpoints can cover supported AWS services. If your IPv4-only application also calls a public payment, email or other external API, those endpoints alone are not enough. Keep an appropriate outbound route.

In the example below, replacing NAT with four interface endpoints lowers the monthly networking subtotal from US$77.50 to US$59.40. Keeping NAT and adding those endpoints raises the external-API design from US$78.40 to US$133.30. The connections you need determine which comparison applies.

Start with the application’s connections

Consider one Linux Fargate application on platform version 1.4.0 or later. Its tasks run in private IPv4 subnets across two Availability Zones in US East (Ohio), us-east-2. It pulls a private ECR image, sends logs to CloudWatch Logs and receives a secret through its task definition.

One version of the application needs only those AWS services. Another also calls an external IPv4 API. We keep that difference visible throughout the comparison.

ConnectionPrivate route for this exampleWhat to check
ECR authentication and image detailsecr.api interface endpointTask execution role permissions and private DNS
ECR registryecr.dkr interface endpointHTTPS access and private DNS
Container image layersS3 gateway endpointBoth task route tables and access to ECR’s regional layer bucket
Container logslogs interface endpointExisting log group and execution role permissions
Secret injected at task startupsecretsmanager interface endpointExecution role access to the secret and its encryption key, where required
External IPv4 APINAT or another approved internet-access pathThe API’s actual hostname, port and access requirements

AWS documents the ECR API, registry and S3 endpoint requirements. Secrets Manager endpoints provide private access to that service; they do not supply IAM permission by themselves.

List additional connections your application makes, including SSM Parameter Store, STS, KMS, telemetry and third-party APIs. A task that retrieves a secret at runtime uses its application task role, which may differ from the execution role used at startup. Add the correct endpoint and permissions for the actual caller.

Compare the two network designs

A NAT gateway lets private IPv4 tasks initiate connections to public addresses. A VPC interface endpoint gives private access to a particular supported service. An S3 gateway endpoint adds routes for regional S3 traffic and has no additional endpoint hourly or data-processing charge.

Design A: a NAT gateway in each Availability Zone

Availability Zone A

Fargate task
Private subnet · no public IP
Public NAT gateway in AZ A
Public subnet · one Elastic IP
Internet gateway → public AWS service addresses and external APIs

Availability Zone B

Fargate task
Private subnet · no public IP
Public NAT gateway in AZ B
Public subnet · one Elastic IP
Internet gateway → public AWS service addresses and external APIs
Image-layer traffic
from both task subnets
S3 gateway endpoint
on both route tables
ECR image layers
stored in S3

Each task uses its own AZ’s NAT gateway. S3 image layers use the gateway endpoint instead of passing through NAT.

Design B: private connections to the four AWS services

Availability Zone A

Fargate task
Private subnet · no public IP
Four interface endpoint network connections
ECR API · ECR registry · Logs · Secrets
AWS services over private connections

Availability Zone B

Fargate task
Private subnet · no public IP
Four interface endpoint network connections
ECR API · ECR registry · Logs · Secrets
AWS services over private connections
Image-layer traffic
from both task subnets
S3 gateway endpoint
on both route tables
ECR image layers
stored in S3

An endpoint connection is available in each AZ. DNS and routing determine which one a task uses. External IPv4 APIs still need a separate outbound path.

The diagrams show outbound traffic. An internet-facing load balancer can still send customer requests to private tasks; that incoming path is separate. A public subnet alone does not give a Fargate task internet access when the task has no public IP. AWS explains the public and private subnet options.

The NAT example uses two zonal public NAT gateways. AWS also offers regional NAT gateways, billed by active AZ and processed data. Account for every active AZ and public address when pricing that design. IPv6 and managed outbound proxies are other designs to assess separately against all of your dependencies.

Four interface endpoints across two AZs means eight billed endpoint network connections. Merely placing endpoints in both AZs does not guarantee every request remains within its AZ; check DNS resolution and traffic paths if cross-AZ charges matter.

Compare the monthly networking costs

Rates checked on 28 November 2026 for US East (Ohio). The calculation uses 730 hours, two NAT gateways where needed, one public IPv4 address per NAT gateway, and four interface endpoints in each of two AZs where needed. Both designs already use an S3 gateway endpoint.

ChargeRate usedMonthly fixed cost
NAT gateway hoursUS$0.045 per gateway-hour2 × 730 × US$0.045 = US$65.70
NAT public IPv4 addressesUS$0.005 per address-hour2 × 730 × US$0.005 = US$7.30
NAT data processingUS$0.045 per GBDepends on traffic through NAT
Interface endpoint hoursUS$0.01 per endpoint-AZ-hour4 × 2 × 730 × US$0.01 = US$58.40
Interface endpoint processingUS$0.01 per GB in the first 1 PB monthly regional tierDepends on traffic through the endpoints
S3 gateway endpointNo endpoint hourly or processing chargeUS$0.00 in both designs

Sources: AWS NAT gateway and public IPv4 pricing, AWS PrivateLink pricing, and the Ohio VPC price list. Rates can change. The 730-hour month is a calculation assumption; actual billable time can differ.

Assume 100 GB per month, counting requests and responses, goes through the four AWS interface services. Image-layer downloads use the S3 gateway route and are outside that 100 GB. The external-API version also processes 20 GB through NAT.

Application needsDesignFixed costProcessingMonthly subtotal
AWS services onlyNAT + S3 gatewayUS$73.00100 × US$0.045 = US$4.50US$77.50
AWS services onlyInterface endpoints + S3 gatewayUS$58.40100 × US$0.01 = US$1.00US$59.40
AWS services + external APINAT + S3 gatewayUS$73.00120 × US$0.045 = US$5.40US$78.40
AWS services + external APINAT + interface endpoints + S3 gatewayUS$131.40100 × US$0.01 + 20 × US$0.045 = US$1.90US$133.30

These are networking subtotals. Add internet data transfer, cross-AZ and cross-region transfer where applicable, Fargate, load balancer charges and its public addresses, ECR storage, S3 requests, logging, secrets, taxes and other services. No free-tier allowance or discount is included.

When does adding endpoints pay for itself?

If NAT must remain, moving eligible traffic from US$0.045 to US$0.01 per GB saves US$0.035 per GB in processing. Four endpoints across two AZs add US$58.40 per month. That needs about 1,669 GB per month of eligible traffic to cover the added endpoint hours: 58.40 ÷ 0.035. This threshold excludes transfer differences and assumes the same pricing tier.

A smaller endpoint set has a different threshold. For example, routing image layers through the S3 gateway can avoid NAT processing without adding interface endpoint hours for that S3 traffic. Choose endpoints for their access requirements as well as their cost. Keep a required private connection even when it is not the cheapest option.

Run the cost calculation on your computer

Save this as fargate_network_costs.py and run it with Python 3. It makes no network requests and needs no AWS credentials. Read the code usage and safe-use terms before using the examples.

# Copyright 2026 Anrotex IT Systems LLP.
# Learning and evaluation only: https://www.anrotex.com/downloads-policy
from decimal import Decimal


def monthly_cost(*, nat, endpoints, aws_gb, internet_gb):
    """Ohio rates checked 28 November 2026; two AZs, 730 hours.

    aws_gb is traffic through the four interface services, not S3 layers.
    Both designs use an S3 gateway endpoint. Transfer and app costs are extra.
    The interface rate assumes the first 1 PB monthly pricing tier.
    """
    aws_gb, internet_gb = Decimal(str(aws_gb)), Decimal(str(internet_gb))
    if any(not value.is_finite() or value < 0 for value in (aws_gb, internet_gb)):
        raise ValueError("Traffic must be finite and non-negative.")
    if internet_gb and not nat:
        raise ValueError("This design has no route to the external IPv4 API.")
    if aws_gb and not (nat or endpoints):
        raise ValueError("Choose a route to the AWS services.")
    total = Decimal("0")
    if nat:
        total += 2 * 730 * (Decimal("0.045") + Decimal("0.005"))
        total += (internet_gb + (0 if endpoints else aws_gb)) * Decimal("0.045")
    if endpoints:
        total += 4 * 2 * 730 * Decimal("0.01")
        total += aws_gb * Decimal("0.01")
    return total.quantize(Decimal("0.01"))


if __name__ == "__main__":
    for label, nat, endpoints, internet_gb in [
        ("AWS only / NAT", True, False, 0),
        ("AWS only / endpoints", False, True, 0),
        ("External API / NAT", True, False, 20),
        ("External API / NAT + endpoints", True, True, 20),
    ]:
        cost = monthly_cost(nat=nat, endpoints=endpoints, aws_gb=100, internet_gb=internet_gb)
        print(f"{label}: US${cost}")
python3 fargate_network_costs.py
AWS only / NAT: US$77.50
AWS only / endpoints: US$59.40
External API / NAT: US$78.40
External API / NAT + endpoints: US$133.30

The calculation checks also cover idle-month charges, invalid traffic inputs, a missing internet route and the break-even point. Change the traffic inputs to explore your workload; update the rates and endpoint count if your design differs. The first-tier endpoint rate assumes total regional interface traffic remains within that tier.

Check the private endpoint configuration

This Terraform example adds the four interface endpoints and the ECR image-layer route to an existing, separate Ohio test VPC. It requires two subnets in different AZs, their two route tables, the task security group and an existing execution role. It does not create the VPC, tasks, NAT gateways, IAM roles or default internet routes.

The VPC needs DNS support and DNS hostnames enabled. Existing task egress and network ACLs must permit HTTPS to the endpoints and S3. The interface security group accepts HTTPS only from the supplied task security group. Endpoint policies restrict access to the named execution role; that role must still have the appropriate IAM permissions.

The S3 policy allows image-layer reads from ECR’s Ohio bucket. If your application also uses other S3 buckets, add their required permissions before associating this endpoint with its route tables. Otherwise, moving S3 traffic onto the endpoint can block those requests. Check for existing endpoints and private DNS conflicts first.

Show main.tf
# Copyright 2026 Anrotex IT Systems LLP.
# Learning and evaluation only: https://www.anrotex.com/downloads-policy
terraform {
  required_version = ">= 1.7, < 2.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "= 6.70.0"
    }
  }
}

variable "network" {
  description = "Existing Ohio test VPC, task group, two subnets in different AZs and their route tables."
  type = object({
    vpc_id                 = string
    task_security_group_id = string
    subnet_ids             = set(string)
    route_table_ids        = set(string)
  })
  validation {
    condition     = length(var.network.subnet_ids) == 2 && length(var.network.route_table_ids) == 2
    error_message = "Supply two distinct subnet IDs and two distinct route table IDs."
  }
}

variable "task_execution_role_arn" {
  description = "Existing task execution role with scoped image, logging and secret permissions."
  type        = string
  validation {
    condition     = can(regex("^arn:aws:iam::[0-9]{12}:role/.+$", var.task_execution_role_arn))
    error_message = "Supply the full AWS IAM task execution role ARN."
  }
}

provider "aws" {
  region              = "us-east-2"
  allowed_account_ids = [split(":", var.task_execution_role_arn)[4]]
}

locals {
  service_actions = {
    "ecr.api"      = ["ecr:GetAuthorizationToken", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
    "ecr.dkr"      = ["ecr:GetAuthorizationToken", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
    logs           = ["logs:CreateLogStream", "logs:PutLogEvents"]
    secretsmanager = ["secretsmanager:GetSecretValue"]
  }
}

resource "aws_security_group" "endpoints" {
  name_prefix = "fargate-endpoints-"
  description = "HTTPS from the supplied ECS task security group only"
  vpc_id      = var.network.vpc_id
  ingress {
    description     = "Task connections to AWS interface endpoints"
    from_port       = 443
    to_port         = 443
    protocol        = "tcp"
    security_groups = [var.network.task_security_group_id]
  }
  egress = []
}

resource "aws_vpc_endpoint" "service" {
  for_each            = local.service_actions
  vpc_id              = var.network.vpc_id
  service_name        = "com.amazonaws.us-east-2.${each.key}"
  vpc_endpoint_type   = "Interface"
  subnet_ids          = var.network.subnet_ids
  security_group_ids  = [aws_security_group.endpoints.id]
  private_dns_enabled = true
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { AWS = var.task_execution_role_arn }
      Action    = each.value
      Resource  = "*"
    }]
  })
}

resource "aws_vpc_endpoint" "image_layers" {
  vpc_id            = var.network.vpc_id
  service_name      = "com.amazonaws.us-east-2.s3"
  vpc_endpoint_type = "Gateway"
  route_table_ids   = var.network.route_table_ids
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = "*"
      Action    = "s3:GetObject"
      Resource  = "arn:aws:s3:::prod-us-east-2-starport-layer-bucket/*"
    }]
  })
}

The example uses an execution role for image pulls, log delivery and startup secret injection. If application code calls these services using another role, review the endpoint policy for that caller too. Existing log groups, secret permissions and any required KMS permissions remain your responsibility. AWS provides further guidance on CloudWatch Logs endpoints and testing.

Run the configuration tests without creating resources

Use Terraform 1.7 or later. Save main.tf and the following endpoints.tftest.hcl in a new directory. The test uses Terraform’s mock AWS provider and sample IDs, so it checks the planned configuration without making AWS API calls.

Show endpoints.tftest.hcl
# Copyright 2026 Anrotex IT Systems LLP.
# Learning and evaluation only: https://www.anrotex.com/downloads-policy
mock_provider "aws" {}

variables {
  network = {
    vpc_id                 = "vpc-00000000000000001"
    task_security_group_id = "sg-00000000000000001"
    subnet_ids             = ["subnet-00000000000000001", "subnet-00000000000000002"]
    route_table_ids        = ["rtb-00000000000000001", "rtb-00000000000000002"]
  }
  task_execution_role_arn = "arn:aws:iam::123456789012:role/test-task-execution"
}

run "private_service_connections" {
  command = plan
  assert {
    condition     = toset(keys(aws_vpc_endpoint.service)) == toset(["ecr.api", "ecr.dkr", "logs", "secretsmanager"])
    error_message = "Keep all four services required by this application."
  }
  assert {
    condition     = alltrue([for endpoint in aws_vpc_endpoint.service : endpoint.private_dns_enabled && length(endpoint.subnet_ids) == 2 && endpoint.vpc_endpoint_type == "Interface"])
    error_message = "Each interface endpoint needs private DNS and both test subnets."
  }
  assert {
    condition     = length(aws_security_group.endpoints.ingress) == 1 && alltrue([for rule in aws_security_group.endpoints.ingress : rule.from_port == 443 && rule.to_port == 443 && rule.protocol == "tcp" && rule.security_groups == toset([var.network.task_security_group_id]) && length(coalesce(rule.cidr_blocks, [])) == 0 && length(coalesce(rule.ipv6_cidr_blocks, [])) == 0])
    error_message = "Only the task security group may initiate HTTPS connections."
  }
  assert {
    condition     = alltrue([for endpoint in aws_vpc_endpoint.service : jsondecode(endpoint.policy).Statement[0].Principal.AWS == var.task_execution_role_arn])
    error_message = "Interface policies must stay limited to the supplied execution role."
  }
  assert {
    condition     = aws_vpc_endpoint.image_layers.route_table_ids == var.network.route_table_ids && jsondecode(aws_vpc_endpoint.image_layers.policy).Statement[0].Resource == "arn:aws:s3:::prod-us-east-2-starport-layer-bucket/*" && jsondecode(aws_vpc_endpoint.image_layers.policy).Statement[0].Action == "s3:GetObject"
    error_message = "Both route tables need read access to the regional ECR layer bucket."
  }
}

run "reject_one_subnet" {
  command = plan
  variables {
    network = {
      vpc_id                 = "vpc-00000000000000001"
      task_security_group_id = "sg-00000000000000001"
      subnet_ids             = ["subnet-00000000000000001"]
      route_table_ids        = ["rtb-00000000000000001", "rtb-00000000000000002"]
    }
  }
  expect_failures = [var.network]
}
terraform init -backend=false
terraform fmt -check
terraform validate
terraform test

init downloads the pinned AWS provider and writes local setup files. The checks verify the four endpoints, private DNS, two supplied subnets, HTTPS access, execution-role restrictions and the S3 image-layer route. They also reject a configuration with only one subnet.

Configuration tests do not prove that real subnet IDs belong to different AZs or that a running application can connect. Use the checks below in staging before removing any working route. Review any real Terraform plan with your infrastructure owner; applying it creates billable endpoints and changes S3 routing.

Test every connection before changing production

  1. Confirm the network. Check that both task subnets belong to the intended VPC and different AZs. Inspect their route tables, DNS settings, task egress, endpoint security groups and network ACLs.
  2. Start a new task in each AZ. Use the intended image and task definition. Confirm that the image pulls, the application starts and the health check passes.
  3. Check new logs. Find the log stream for each new task and verify that fresh entries arrive. Old logs do not prove the new route works.
  4. Check secret use. Confirm the intended secret is available to the application without printing its value. Exercise the application operation that needs it.
  5. Check external calls. Use the external provider’s test environment and a harmless operation. A basic health check may pass while payment or email requests fail.
  6. Prove the selected path. In an isolated staging subnet, test the endpoint design without a default NAT route. A successful test while NAT remains available can hide a missing endpoint. Restore the staging route if a required connection fails.
  7. Repeat after a replacement. Launch a replacement task and repeat the checks. Keep the previous working configuration available until the agreed checks pass.

AWS documents an extra requirement for the first pull through an ECR pull-through cache: it can still require NAT. Windows images can have external layer dependencies too. The Linux private-image example here does not remove those exceptions.

If a task fails before your application logs appear, follow our ECS stopped-task guide. Separate networking failures from missing IAM permissions, image errors and application startup problems.

Choose the design that fits the workload

  • Only supported AWS connections: assess whether endpoints cover every startup and runtime dependency, then compare their full cost with NAT.
  • External IPv4 APIs: preserve a suitable outbound route. Add endpoints where access controls or enough eligible traffic justify them.
  • NAT processing dominated by S3: investigate the S3 gateway route first, including the endpoint policy and every affected bucket.
  • Unclear dependencies: map connections and test them before changing routes. Record expected charges and compare billed usage after the change.

Use our AWS cost-review worksheet to record the traffic, proposed change, owner and checks. For new ECS infrastructure, see the Terraform AWS Foundation.

For an existing workload, our US$500 AWS Infrastructure Review covers one account and region, and up to 20 agreed resources. It provides findings and a practical action plan; implementation is scoped separately. Preview the findings and action plan.

Discuss your AWS networking costs