How do resources in different subnets within the same VPC communicate with each other?
Route tables to the rescue.
EC2 A in subnet A (CIDR 10.0.0.0/24) and EC2 B in subnet B (CIDR 10.0.1.0/24) are both in the same VPC. They can communicate with each other because the main route table contains a route with the destination “10.0.0.0/16” and the target “local”. This route allows all resources within the VPC’s CIDR block (10.0.0.0/16) to communicate with each other internally. Since the IP addresses of EC2 A and EC2 B both fall within this CIDR block, they can talk to each other.
The “local” target in the main route table is automatically created for every VPC and enables internal communication between all subnets within the VPC.
Another thing to keep in mind: security groups and network ACLs must also allow the necessary traffic; the route table alone does not guarantee communication if these are too restrictive.
Then the next question: how do resources in a subnet within a VPC talk to resources outside the VPC (aka, the internet)?
This is done using a combination of an Internet Gateway and a record in the route table. The destination in this record is 0.0.0.0/0 (which basically means ALL the IP addresses) and the target is the internet gateway.
Now if EC2 A wants to send a package to an IP address on the internet like 192.168.45.123, it will be routed to the Internet Gateway because that is what the record in the route table defined (again, 0.0.0.0/0: ALL the IP addresses). Keep in mind that the EC2 instance also needs a public IP address in order to speak to any other machine on the internet.
So to summarize: if you want your EC2 instance in a subnet to be able to talk to other machines on the internet, you need to:
- Have an Internet Gateway.
- Have a record in the route table destination: 0.0.0.0/0. Target: the Internet Gateway.
- Attach a public IP address to the EC2 instance.