how to create nat gateway
To connect a private EC2 instance to the internet using a NAT Gateway, follow these steps:
🧭 Scenario
You have a private EC2 instance in a private subnet.
You want it to access the internet (e.g., for updates, API calls) without exposing it publicly.
You use a NAT Gateway in a public subnet to do that.
✅ Step-by-Step Setup
1. Create a Public Subnet (if not already created)
CIDR: e.g.,
10.0.1.0/24Enable Auto-assign public IP
Associate with a route table that points to:
Destination: 0.0.0.0/0 → Target: Internet Gateway (IGW)
2. Create a NAT Gateway
Go to VPC → NAT Gateways
Choose:
Subnet: your public subnet
Elastic IP: allocate a new one or pick existing
Click Create NAT Gateway
3. Create or Modify a Private Subnet Route Table
Go to Route Tables
Choose the one associated with your private subnet (where your EC2 lives)
Edit routes:
Destination: 0.0.0.0/0 → Target: NAT Gateway (nat-xxxxxxxx)
4. Launch EC2 into Private Subnet
Choose subnet without auto-assigned public IP
Use private IP only
Ensure security group allows outbound to internet (e.g.,
0.0.0.0/0for HTTP/HTTPS)
5. Test Internet from Private EC2
SSH into a public EC2 (bastion) or use SSM if enabled, then from private EC2:
curl https://google.com
Should return HTML output ✅
✅ SSH into a Public EC2 Instance
Prerequisites:
You have the
.pemkey file (private key)EC2 has a public IP
Port 22 (SSH) is open in the Security Group
🔐 Command:
ssh -i your-key.pem ubuntu@<public-ip>
Example:
ssh -i demokey.pem ubuntu@3.95.123.45
🔒 SSH into a Private EC2 Instance
A private EC2 does not have a public IP, so you must:
Option 1: Use a Bastion Host (Jump Box)
# Step 1: SSH into the public EC2 (bastion)
ssh -i demokey.pem ubuntu@<public-ip>
# Step 2: From inside that EC2, SSH into the private one
ssh -i demokey.pem ubuntu@<private-ip>
Make sure:
Both EC2s are in the same VPC
The private EC2's Security Group allows SSH from the bastion's private IP or Security Group
Option 2: Use SSM Session Manager (no need for SSH or public IP)
If enabled, run from your local machine:
aws ssm start-session --target <instance-id>
