AWS ‐ Best Practices - FullstackCodingGuy/Developer-Fundamentals GitHub Wiki

Why Do We Need Public and Private Subnets in AWS?

read

Why Do We Need Public and Private Subnets in AWS?

When designing secure, scalable cloud architectures, it's important to separate public-facing resources from private, internal resources. AWS uses Public Subnets and Private Subnets to achieve this.


📌 Public Subnet vs. Private Subnet

Feature Public Subnet Private Subnet
Internet Access Yes (via Internet Gateway) No (needs NAT Gateway)
Use Case Hosting public resources (e.g., web servers, API gateways) Hosting internal resources (e.g., databases, backend apps)
Route Table Direct route to Internet Gateway No direct internet access (uses a NAT Gateway if needed)
Security Exposed to the internet Internal network, not publicly accessible
Connectivity Public IPs allowed Private IPs only

📌 Why Do We Need Both?

1️⃣ Security

  • Public Subnet: Hosts resources that need internet access (e.g., a web server).
  • Private Subnet: Keeps sensitive resources isolated (e.g., databases, backend services).

2️⃣ Best Practice

  • AWS recommends placing databases and internal apps in private subnets for security.
  • Only expose what’s necessary via Load Balancers or API Gateways in a public subnet.

3️⃣ Outbound Internet Access (for Private Subnet)

  • Private subnets cannot access the internet directly.
  • To download packages (e.g., npm modules in Lambda), you need a NAT Gateway in a Public Subnet.

📌 Example Architecture

🔹 VPC with Public & Private Subnets

VPC (10.0.0.0/16)
│
├── Public Subnet (10.0.1.0/24)  
│   ├── NAT Gateway (for outbound access)
│   ├── API Gateway / ALB (for external requests)
│
├── Private Subnet (10.0.2.0/24)  
│   ├── Lambda Function  
│   ├── DocumentDB  
│   ├── RDS Database  
│  
└── Internet Gateway (for public access)

🔹 Networking Flow

  1. User → API Gateway → Lambda (in Private Subnet) → DocumentDB
  2. Lambda (in Private Subnet) → NAT Gateway (in Public Subnet) → Internet (for updates)

📌 Do You Need a Public Subnet for Lambda to Connect to DocumentDB?

🚀 NO!

  • Lambda needs to be inside a Private Subnet to connect to DocumentDB.
  • But if Lambda needs internet access (e.g., fetching dependencies), then a NAT Gateway in a Public Subnet is needed.

🔥 Conclusion

  • Public Subnet → For internet-facing resources (APIs, ALB, NAT Gateway).
  • Private Subnet → For secure backend resources (Databases, internal services).
  • Use a NAT Gateway in a Public Subnet if private resources need outbound internet access.

Lambda and Amazon DocumentDB

read
⚠️ **GitHub.com Fallback** ⚠️