访问 VPC 中的数据库
学习将 Lambda 函数连接到关系型数据库(例如 RDS)以及位于私有 VPC 网络中的其他数据存储的最佳实践
访问 VPC 中的数据库 是 CoddyKit 上的免费 Serverless AWS Lambda Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless AWS Lambda Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless AWS Lambda Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Connect Lambda to Private DBs
Welcome! In this lesson, you'll learn how to securely connect your Lambda functions to databases that reside within your private Amazon Virtual Private Cloud (VPC).
This is crucial for serverless applications that need to interact with sensitive or internal data stores like Amazon RDS or other databases that aren't publicly accessible.
Lambda & Your Private Database
You've already configured your Lambda function to operate within a VPC (from the previous lesson). Now, we'll focus on how that Lambda can reach a database that's also inside the same VPC.
This setup ensures secure, internal communication, keeping your database isolated from the public internet.
Security Groups: The Gatekeepers
Security Groups are fundamental here. Think of them as virtual firewalls for your instances and resources within a VPC.
- They control both inbound (incoming) and outbound (outgoing) traffic.
- Both your Lambda function and your database will have associated security groups.
- These groups must be configured to explicitly allow communication between them.
Database Inbound Rules
Your database's security group needs an inbound rule to allow connections from your Lambda function.
- Type: Custom TCP
- Port Range: The specific port your database listens on (e.g.,
3306for MySQL,5432for PostgreSQL). - Source: Crucially, this should be the Security Group ID of your Lambda function.
This ensures only your Lambda can initiate connections to the database.
Lambda Outbound Rules
Conversely, your Lambda function's security group needs an outbound rule to allow it to send traffic to your database.
- Type: Custom TCP
- Port Range: Again, the database's specific port (e.g.,
3306). - Destination: This should be the Security Group ID of your database.
This allows your Lambda to successfully reach out and connect to the database.
Subnets & Network Reachability
Beyond security groups, ensure your Lambda function is deployed into subnets that have proper network routing access to the subnets where your database instances reside.
- Typically, both Lambda and the database will be placed in private subnets within the same VPC.
- AWS handles the internal routing within the VPC, but proper subnet association is key for reachability.
Connecting from Lambda Code
Inside your Lambda function's code, you'll use standard database drivers and connection strings, just like any other application.
You'll need these key details:
- Database endpoint: (e.g.,
your-db.xxxx.rds.amazonaws.com) - Port: (e.g.,
3306) - Database name
- Username
- Password
Java DB Connection Example
Here's a conceptual Java snippet demonstrating how a Lambda might attempt to connect to a database. In a real application, you would handle credentials securely.
This example shows the basic structure; it won't run successfully without a live database and environment variables set.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String dbUrl = System.getenv("DB_URL");
String dbUser = System.getenv("DB_USER");
String dbPass = System.getenv("DB_PASS");
if (dbUrl == null || dbUser == null || dbPass == null) {
System.out.println("Error: DB environment variables not set.");
return;
}
try {
System.out.println("Attempting to connect to database...");
Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
System.out.println("Connection successful!");
conn.close();
} catch (SQLException se) {
System.err.println("Database connection error: " + se.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
}
}
}Securely Manage Credentials
Never hardcode database credentials directly in your Lambda code! This is a major security risk.
Best practices for managing sensitive information:
- AWS Secrets Manager: The recommended way to store, retrieve, and rotate database credentials securely.
- Environment Variables: Suitable for non-sensitive configuration, but not for passwords or API keys.
Always prioritize security for sensitive data.
Check Your Understanding
Imagine your Lambda function (associated with Security Group SG-A) needs to connect to an RDS database (associated with Security Group SG-B) on port 3306.
Which inbound rule must be configured on SG-B (the database's security group) to allow this connection?
Recap: Database Access in VPC
Great job! You've learned the essentials of connecting your Lambda functions to private databases within your VPC.
- Both your Lambda and database must be in the same VPC.
- Security groups are vital for controlling traffic flow between them.
- Configure inbound rules on the database's SG and outbound rules on Lambda's SG.
- Always manage database credentials securely, ideally using AWS Secrets Manager.
This knowledge is key to building secure and robust serverless applications!
常见问题解答
「访问 VPC 中的数据库」课时是免费的吗?
是的 — 「访问 VPC 中的数据库」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless AWS Lambda Development 课程的其余内容,请升级到 CoddyKit PRO。 Serverless AWS Lambda Development 课程共包含 4 节课。
「访问 VPC 中的数据库」这节课中我会学到什么?
学习将 Lambda 函数连接到关系型数据库(例如 RDS)以及位于私有 VPC 网络中的其他数据存储的最佳实践 你通过在浏览器中直接运行的动手代码来练习 Serverless AWS Lambda Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Serverless AWS Lambda Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Serverless AWS Lambda Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「访问 VPC 中的数据库」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Serverless AWS Lambda Development 课中编写并运行代码吗?
能。每节 Serverless AWS Lambda Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。