Allow internet access for ec2 instances with private IP addresses inside a public subnet?

  • I have a public subnet(S1) with a route pointing to the internet gateway in its route table.
  • Launched an ec2 instance(I1) inside S1 but did not allocate a public IP to it, thereby the instance only has a private IP address and cannot be reached from the internet.
  • I have setup path based routing from my gateway to the instance(I1) which works just fine, meaning requests to the gateway are being served without hindrances.
  • The problem is I need to access some resource in the internet from my instance I1 but the instance should not be reachable from outside.

Am I wrong in thinking that the instance could communicate to the internet via the gateway(Just like how a mobile with a private IP inside a wifi network talks to the internet via the access point's public IP)?!

Just wanted to know if this case can be achieved without assigning a public IP/Elastic IP to my instance because you need internet access for installing any software too, how would people implement this requirement?!

NOTE: For private subnets NAT gateway works just fine but this is a public subnet, if you point it to a NAT gateway, you need to remove the route pointing to internet gateway, meaning my gateway will not be able to communicate with my instance(Because ALB/Gateway only communicates to instances ina public subnet in AWS?!)

P.S.: Beginner in aws, please don't abuse for any knowledge-gaps, thanks in advance.

--Yash


You are misunderstanding / misusing Public and Private subnets.

A public subnet has an Internet gateway (IGW). Instances in the public subnet need public IP addresses to access the Internet.

A private subnet has a NAT Gateway or NAT Instance. Instances in a private subnet do not have public IP addresses.

In summary: if a subnet has an IGW it is a public subnet. If a subnet has a NAT it is a private subnet.

Solution for your issue:

  1. Create a new subnet.
  2. Create a NAT Gateway. Assign the NAT Gateway to the subnet.
  3. Create an AMI for each of your instances that you need to move to the private subnet and then shut those instances down. Later you can terminate them but wait until you know that the following steps completed correctly.
  4. Launch new EC2 instances from each of the AMIs that you created in step #3.
  5. Verify everything is working. Then terminate the old instances. Your AMIs also serve as backups for those instances.

What helps with your requirement is:

"You can use public IP addresses on your instance and then lock them down with security groups. The risk depends on what type of access is allowed and from where."