VPC is a logically isolated environment in your Public cloud where you can launch your resources like servers, databases, etc. It's like having a Private villa where you can use anything you like, & you pay only for things you use inside your villa. VPC gives you a private cloud, within a public cloud.
Security
Our private villa has guards at the main gate & for each room.
Guards at the main gate?
Internet Gateway
Internet Gateway - Allows communication between your resources inside VPC, & the outside Internet.
Guards for each room?
Security Groups
Security Groups - Firewall for each resource.
Subnets
An IP address range is used to define a VPC. ( Eg. 10.5.0.0/16 )
In the IPv4 address, you have 32 bits, so in 10.5.0.0/16 - 16 bits are reserved for the network - (10.5) & the other 2 digits - (0.0) are for machines.
Using Subnets you can divide your vpc into multiple logical networks. Subnets allow to you give different access rules to your resources inside it.
Why do we need subnets?
- With subnets, network traffic travels shorter distances without passing through unnecessary routers to reach the destination.
Public vs Private Subnet
- A Subnet with an Internet gateway is a Public subnet. So it's accessible for the outside world. Normally, load balancers are kept in public subnets.
Does that mean Private subnets don't have access to the internet?
- No, they use a NAT gateway to access the internet.
BUT Why do ec2-instances inside public/private subnets need to access the Internet?
- To download any software, packages or updates.
Route Tables
Defines the path to reach the destination. It's applied at the VPC & subnet level. Each rule has a target & destination.
What is a Target?
- The thing used to send traffic to the destination. It can be a local (destination is inside vpc) internet gateway, virtual private gateway, or NAT gateway.
IG vs VPG vs NAT gateway vs local
Internet Gateway is a bridge for communication between resources inside VPC & internet.
A virtual private gateway is used to establish a VPN connection between the on-premises data centre & AWS VPC.
NAT gateway allows multiple instances in a private subnet to communicate with the internet, with one public IP address.
local is used for communication within VPC.
To check the local routes on the Route table -
aws ec2 describe-route-tables \
--query 'RouteTables[].Routes[?GatewayId==`local`].DestinationCidrBlock' \
SG vs NACL
Security groups (SG) are applied at the ec2-instance level, each instance has at least 1 SG. It acts as a firewall for the server where you explicitly define the traffic to be ALLOWED both inbound & outbound.
Command to allow an inbound traffic on a security group -
aws ec2 authorize-security-group-ingress \
--group-id $sg_id \
--protocol tcp \
--port 22 \
--cidr $IP
The network access control list (NACL) is applied at the subnet level. Here you can both ALLOW & DENY traffic.