Paying for public IPv4 on AWS: finding every address and moving Fargate tasks behind NAT
Every public IPv4 address on AWS costs $3.65 a month, used or idle. How I counted all of ours from the network interfaces, grouped them by owner, and moved Fargate tasks to private subnets: about 25 addresses down to 13.
The October bill had a line called "VPC" for $90.94. There was no VPC feature behind it that we had turned on. It was public IPv4 addresses, about 25 of them, at $0.005 an hour each. That's $3.65 a month per address, and AWS charges it whether the address carries traffic or sits idle.
In this blog we will find every public address in a region, group them by what owns them, and move Fargate tasks to private subnets so they don't need one. This was one part of the 31% bill cut. The cleanup saved $44.08 a month. Small, but it's the kind of saving that keeps coming every month for no work. Why pay for an address nobody calls?
Seeing it on the bill first
Cost Explorer shows public IPv4 under usage types like APS3-PublicIPv4:InUseAddress and APS3-PublicIPv4:IdleAddress (APS3 is Mumbai; other regions have other prefixes). Group last month by usage type and filter to the VPC service:
aws ce get-cost-and-usage \
--time-period Start=2026-10-01,End=2026-11-01 \
--granularity MONTHLY \
--metrics UnblendedCost UsageQuantity \
--filter '{"Dimensions": {"Key": "SERVICE", "Values": ["Amazon Virtual Private Cloud"]}}' \
--group-by Type=DIMENSION,Key=USAGE_TYPE
UsageQuantity here is address-hours. Divide by 730 and you get the average number of addresses for the month. Ours came to roughly 25.
Idle addresses are the easy ones: an Elastic IP allocated and attached to nothing. The in-use ones are trickier, because "in use" only means attached. It doesn't mean anything ever reached the address.
Finding every address
The bill says how many. To know whose, ask the network interfaces. Every public IPv4 on AWS sits on an ENI: ECS tasks in awsvpc mode, NAT gateways, load balancers, EC2 instances.
aws ec2 describe-network-interfaces \
--filters Name=association.public-ip,Values='*' \
--output json > enis.json
aws ec2 describe-addresses --output json > eips.json
Second call is for Elastic IPs that are not attached anywhere. They don't show up on any interface, but they're billed too.
Then a small script groups them by owner. The owner comes from the interface description: ECS puts the attachment ARN there, NAT gateways say "Interface for NAT Gateway", and load balancers start with "ELB".
#!/usr/bin/env python3
"""Group every public IPv4 address in a region by what owns it.
Usage:
aws ec2 describe-network-interfaces --output json > enis.json
aws ec2 describe-addresses --output json > eips.json
python3 public_ips.py enis.json eips.json
"""
import json
import sys
from collections import Counter
PRICE_PER_HOUR = 0.005 # USD per public IPv4 address, in use or idle
HOURS = 730
def owner(eni):
desc = eni.get("Description", "")
if desc.startswith("arn:aws:ecs:"):
return "ECS task"
if desc.startswith("Interface for NAT Gateway") or eni.get("InterfaceType") in ("nat_gateway", "natGateway"):
return "NAT gateway"
if desc.startswith("ELB "):
return "load balancer"
if eni.get("Attachment", {}).get("InstanceId"):
return "EC2 instance"
return f"other ({eni.get('InterfaceType', '?')}: {desc[:40]})"
def main():
enis = json.load(open(sys.argv[1]))["NetworkInterfaces"]
eips = json.load(open(sys.argv[2]))["Addresses"]
counts = Counter()
for eni in enis:
# Every private IP on the interface can carry its own public address.
for p in eni.get("PrivateIpAddresses", []):
if p.get("Association", {}).get("PublicIp"):
counts[owner(eni)] += 1
# Elastic IPs that are allocated but attached to nothing are billed too.
counts["idle Elastic IP"] = sum(1 for a in eips if "AssociationId" not in a)
total = sum(counts.values())
for name, n in counts.most_common():
if n:
print(f"{name:<40} {n:>3} ${n * PRICE_PER_HOUR * HOURS:7.2f}/month")
print(f"{'total':<40} {total:>3} ${total * PRICE_PER_HOUR * HOURS:7.2f}/month")
if __name__ == "__main__":
main()
The loop goes through PrivateIpAddresses, not just the top-level Association. An interface can have secondary private IPs, each with its own public address, and the top-level field only shows the primary one. I tested the script on a hand-made sample with seven task interfaces, a NAT, two ALB interfaces, one instance and one loose Elastic IP. It printed 12 addresses, $43.80 a month. The API model spells the NAT interface type natGateway, but nat_gateway is also around in examples, so the script matches on the description first and accepts both spellings.
An internet-facing ALB has one public address per AZ it's enabled in. Those are paid too. You can't remove them without making the ALB internal, so just count them and move on.
What we found
The most annoying group was four production services. They ran in private subnets, their route tables sent outbound traffic to the NAT gateway, and still each task had assignPublicIp=ENABLED. See, a public IP on a task in a private subnet is useless. There's no route from the internet gateway to it, and outbound traffic leaves through the NAT anyway. Four addresses, $14.60 a month, doing nothing. I never found out how the setting got there, and honestly it didn't matter.
The non-production tasks were the other big group, and that story went in a circle. When we deleted the non-production NAT gateway on 28 October, seven stage and SIT services moved to public subnets with public IPs, so the count went up for three weeks. On 18 November we put a single zonal NAT back and moved all seven to private subnets without public IPs. The NAT story is in its own post.
After both changes it was about 13 addresses only.
Moving a service behind NAT
For one service, the CLI change is a single command. Changing the network configuration starts a new deployment, so it replaces the tasks:
aws ecs update-service \
--cluster my-cluster \
--service my-api \
--network-configuration 'awsvpcConfiguration={subnets=[subnet-0aaa1111,subnet-0bbb2222],securityGroups=[sg-0ccc3333],assignPublicIp=DISABLED}'
You have to pass the full awsvpcConfiguration again, subnets and security groups included. It replaces the old one, it doesn't merge.
In Terraform the same thing is two lines in network_configuration:
resource "aws_ecs_service" "api" {
name = "my-api"
cluster = var.cluster_arn
task_definition = var.task_definition_arn
desired_count = 1
launch_type = "FARGATE"
network_configuration {
subnets = var.private_subnet_ids
security_groups = [var.service_sg_id]
assign_public_ip = false
}
}
We changed the services with the CLI first, one at a time, and then synced the Terraform so the next plan showed no diff. If you do it in the other order, the plan will try to put things back. If you need a refresher on the service resource itself, Deploying a Go API to ECS Fargate behind an ALB with Terraform has the full module.
Before you switch, check these
Three things can break when a task loses its public IP. Check them per service, not once for all.
First, the private subnets need a default route to a NAT gateway. Without it the task can't even pull its image, and the deployment just sits there with tasks stopping on CannotPullContainerError. Our network module also has an S3 gateway endpoint on the private route tables, which is free and keeps ECR's image layers (they come from S3) off the NAT's per-GB charge. Interface endpoints for ECR itself are $0.013 an hour per AZ in Mumbai, so two of them in two AZs is about $38 a month. For our small traffic the NAT was cheaper; I'd only add them if the NAT data line got big.
Second, ALB target health. Tasks behind an ALB keep working from a private subnet, since the ALB talks to the private IP. But do watch the target group till the new tasks are healthy:
aws elbv2 describe-target-health \
--target-group-arn arn:aws:elasticloadbalancing:ap-south-1:111122223333:targetgroup/my-api/0123456789abcdef
Third, outbound allowlists. If a third party allowlists the IP your calls come from, that IP changes to the NAT gateway's Elastic IP. For the non-production move this was the real work: the new NAT's Elastic IP had to go to every third party that allowlists our non-production calls. In production nothing changed, because those four services were already going out through the NAT.
What's left
The 13 that are left are mostly load balancer, NAT gateway and bastion addresses. I'm fine paying for those, the bastions are a separate discussion. On this blog's own server I pay for exactly one, the Elastic IP on the EC2 host, and I'm keeping it since my DNS points at it.
If you run the script and the "other" bucket is not empty, read the description it prints. That's usually where the surprise is.