How to make EC2 instance in private subnet accessible from the internet? (as in being able to visit the website)

I know that one way is to use a load balancer in a public subnet, but for a development server we wouldn't need a load balancer. Is there an alternative option that would allow an application in a private subnet to be reachable from the internet?

If not, then would the best option be to just leave the development server in a public subnet? The database instances would still be in a private subnet.

Upvotes: 2

Views: 17198

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269091

An Amazon EC2 instance in a private subnet will never be directly reachable from the Internet, even if it has a public IP address. This is because a private subnet does not have a Route Table entry that connects the subnet to an Internet Gateway. This is intentional and desired.

So, your options are:

  • Put your instance in a Public Subnet instead of a Private Subnet, or
  • Create a VPN connection to the VPC so you can communicate with resources in the VPC, including the private subnet, or
  • Connect to an instance in the Public Subnet and use Port Forwarding to then obtain a connection with the private instance (see below), or
  • Use a Load Balancer or Proxy in the Public Subnet to forward traffic to the private subnet (one benefit is that it mimics the production setup)

Port Forwarding is a common technique to provide private connectivity to a resource that is not directly accessible. For example:

  • Public-Instance in the public subnet
  • Private-Instance in the private subnet
  • SSH into Public-Instance with port forwarding, which then establishes a connection to Private-Instance
  • Access resources on your local machine and it will actually forward the request to Private-Instance

A sample connection string would be:

ssh -i pemfile ec2-user@public-instance -L 8000:private-instance:80

Any request sent to your local computer's port 8000 would be forwarded to Public-Instance, which would then forward the request to private-instance:80. This will continue as long as the SSH session is in place.

Upvotes: 15

Related Questions