In AWS ECS, how do I ensure my outgoing IP is static?
How do I ensure a static OUTGOING IP address for my applications within Amazon web service: Elastic Container (AWS ECS), while allowing a dynamic ip-address for the different services within the cluster?
First of all, why would I need this? Let me describe the setup of this particular project: I deployed your application to AWS ECS Fargate in a public VPC. I enabled dynamic IP so I could have as many services as possible with their IP addresses (for some reason I don’t want to go into it now). Then I attached a load balancer to the ECS service to receive inbound requests and route it to the target group based on a preset load-balancing algorithm. Suddenly a new product requirement came that required the service to talk to a 3rd party provider. This 3rd party provider requires you to whitelist your IP address so only request from that ip-address is admissible. The problem here is the application is auto-scaled and any one of the application with their own unique IP will be the one talking to the 3rd party api.
My solution
- Create an Elastic IP (EIP)
- Create a NAT Gateway in a Public Subnet
- Go to VPC → NAT Gateways → Create NAT Gateway.
- Select a public subnet (i.e., a subnet with a route to the IGW).
- It needs to be a subnet different from the subnets your application is deployed to in order to prevent request timeout (request timeout causes explained above)
- Assign an Elastic IP (EIP) to the NAT Gateway
- This EIP is your static public IP.
- Update the Route Table of Your Private Subnets
- For each private subnet, edit its route table.
- Add a route for the IP address of the 3rd party application (or 0.0.0.0/0 for all outgoing requests) pointing to the NAT Gateway’s ID.
- Any instance or container in your private subnets now sends internet-bound packets to the NAT Gateway.
From the diagram, if it is a 3rd party request IPAddress, it passes the request through a NAT gateway before going to the Internet gateway. The receiver sees the IP address of the NAT gateway which you can make static. If it isnt the 3rd party request IP address, it uses the internet gateway directly which reflects the IP address of the instance running the application. This way the 3rd party only sees a single IP address, the address of the NAT gateway which is the Elastic IP you created earlier. Why timeout if the NAT gateway is deployed to a subnet the application is deployed in: If you use the same subnet for both the application and the NAT gateway, the route table of the subnets would keep redirecting traffic from within itself to itself thereby causing a loop which eventually leads to request timeout.