How to access an EC2 instance in a private subnet from an EC2 instance in public subnet in same VPC?
Using an EC2 instance for computing is highly effective, but what if you need to connect to an EC2 instance in a private subnet that communicates with another in a public subnet? Here’s a concise guide on how to establish this connection using a bastion host, a key pair, and a NAT instance.
First, let me talk a bit about Bastion host. I know, it sounds unfamiliar for many of us.
BASTION HOST: It is a computer or a bridge between the device and the private network we wanted to connect to. This is designed to ride out the attacks. These are also called as jump boxes or jump servers
CONFIGURATION:
- Public route table associated with the subnet1 and Bastion EC2 instance
- Private route table associated with subnet2 and Private EC2 instance
- NAT Gateway associated with an Elastic IP and connected to the same subnet as of Bastion EC2 instance
- VPC associated with Internet Gateway
SETUP:
Step1: Launch the Bastion instance and ssh into the private ec2 from Bastion instance. (we need to have the pem key of the private ec2 instance) For this, we need to add the Security group of Bastion EC2 to the Private instance, allowing it to ssh into the private instance.
NOTE: While it’s generally advised against sharing the PEM key across accounts due to security risks, we’re doing so here to demonstrate accessibility from a public EC2 instance to a private one.
Step 2: Now, configure the Private route table, add a new route with a destination of 0.0.0.0/0 (all networks) and set the target to the previously configured NAT Gateway. This allows the private EC2 instance to route its traffic through the public subnet, utilizing the NAT gateway as specified in the route.
This way, we can establish a successful connection between the private EC2 instance and the public EC2 instance in different subnets.