同VPC同子网不同安全组的EC2实例无法通信求助
Hey there, let's work through this EC2 security group communication issue together—it's a super common gotcha when setting up multi-service stacks on AWS! Here's a step-by-step breakdown of how to fix your Node ↔ MongoDB connectivity problem:
First, a quick reminder: AWS Security Groups are stateful firewalls—this means you need to account for both inbound and outbound rules, and communication between instances in different security groups requires rules on both sides.
1. Fix the MongoDB Instance's Security Group Inbound Rules
MongoDB listens on port 27017 by default (adjust if you changed the port). This security group needs to explicitly allow traffic from your Node server's security group to this port:
- Add an inbound rule with:
- Type: Custom TCP
- Port Range:
27017(or your custom MongoDB port) - Source: Select the security group ID of your Node EC2 instance (using the security group instead of an IP makes this more resilient if your Node instance's private IP changes)
2. Verify the Node Instance's Security Group Outbound Rules
Your Node server needs to be able to initiate connections to MongoDB, and receive the response traffic:
- By default, security groups allow all outbound traffic (
0.0.0.0/0), but if you've modified this rule:- Ensure there's an outbound rule allowing TCP traffic to port
27017, with the target set to either your MongoDB instance's security group ID or your subnet's private IP range - Note: Since security groups are stateful, if you allow outbound requests to MongoDB, the return traffic will automatically be allowed back in—you don't need a separate inbound rule for the response
- Ensure there's an outbound rule allowing TCP traffic to port
3. Test Connectivity to Validate Fixes
Once you've updated the rules, test from your Node instance to confirm:
# Use telnet to test port connectivity telnet <mongodb-private-ip> 27017 # Or use netcat for more detailed output nc -zv <mongodb-private-ip> 27017
If the connection still fails, double-check that MongoDB is listening on the private IP (not just localhost) by running this on your MongoDB instance:
netstat -plnt | grep mongod
You should see output like 0.0.0.0:27017 or <mongodb-private-ip>:27017—if it only shows 127.0.0.1:27017, you'll need to update your MongoDB config to bind to all interfaces or the private IP.
4. Bonus Best Practices
- Avoid opening port 27017 to
0.0.0.0/0—using security group IDs as sources follows the principle of least privilege and keeps your database secure - Since your instances are in the same subnet, you don't need to worry about route table issues (unless you modified the default subnet routes)—the problem is almost certainly security group-related
- Once you confirm the fix works in the AWS Console, update your CloudFormation template to codify these rules so you don't run into the same issue on future deployments
内容的提问来源于stack exchange,提问作者Jeet

