Lambda与RDS Postgres连接失败,核对VPC子网配置仍未解决
Hey Leonardo, let's walk through the most common missing configurations that cause this exact problem—since you've already aligned the VPC and subnets, here are the key areas to double-check:
Security Group Misconfigurations
This is the #1 culprit! Even if your VPC/subnets match:- Ensure your Lambda's security group allows outbound traffic to port 5432 (Postgres default) to any destination, or specifically to your RDS security group.
- Confirm your RDS security group has an inbound rule allowing traffic from your Lambda's security group (not just public IPs) on port 5432. Don't use a broad IP range here—lock it down to the Lambda SG for security.
Lambda Execution Role Permissions
Lambda needs permissions to create network interfaces (ENIs) in your VPC to connect to resources. Make sure your Lambda execution role has theAWSLambdaVPCAccessExecutionRolemanaged policy attached, or at minimum these permissions:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface" ], "Resource": "*" } ] }Without these, Lambda can't establish a network presence in your VPC at all.
VPC DNS Settings
For Lambda to resolve your RDS endpoint's hostname inside the VPC, your VPC must have:enableDnsSupportset totrue(default, but worth verifying)enableDnsHostnamesset totrue(required for Lambda to resolve private DNS names)
You can check these in the VPC console under "Your VPCs" > Select your VPC > "Actions" > "Edit DNS hostnames/support".
RDS Subnet Group & Endpoint Type
- Ensure your RDS instance is using a subnet group that includes subnets in the same VPC as Lambda. Even if you selected the right VPC, a misconfigured subnet group could isolate RDS.
- Double-check you're using the RDS private endpoint in your Lambda code (not the public endpoint). When you disable public access, the public endpoint stops working—your code should use the private DNS name from the RDS console.
Subnet Route Tables
- If your Lambda is in a public subnet: Make sure the route table doesn't force all traffic through an IGW, but still allows internal VPC traffic to RDS (this is default for VPCs, but custom route tables can break this).
- If your RDS is in a private subnet: Confirm the route table for Lambda's subnet has a route to the private subnet (again, default for same VPC, but worth checking if you've modified routes).
Test with Debug Logs
Add simple logging to your Lambda code to narrow down the issue:- Print the RDS endpoint you're using to confirm it's the private one.
- Catch connection errors and log details (e.g., "DNS resolution failed" vs "connection timed out" vs "authentication failed").
You can also run a quick test in Lambda to check port connectivity to RDS (usingtelnetor a simple TCP client) to rule out network vs authentication issues.
内容的提问来源于stack exchange,提问作者Leonardo

