私有网络下MongoDB跨节点连接异常问题排查求助
Got it, let's break down what's going on here and fix this connection issue step by step. The key clue in your logs—connections being accepted then immediately closed—is super common when running MongoDB in replica set mode but skipping the critical initial configuration step.
First, Verify Your Bind IP Configuration
First, double-check that your --bind_ip parameter is using the actual private IPs of each node (not the placeholder host_private_ip). Run this command on both machines to confirm the running mongod arguments:
ps aux | grep mongod
- On machine A (db1), you should see
--bind_ip localhost,10.20.106.12 - On machine B (db2), you should see
--bind_ip localhost,10.1.0.192
If you still see host_private_ip in the output, replace that placeholder with the node's actual private IP, restart mongod, and retest. But since you confirmed telnet/netcat can reach the port, this is likely configured correctly—so let's focus on the main issue.
The Root Cause: Uninitialized Replica Set
You're starting mongod with --replSet rs1, which puts MongoDB into replica set mode—but you haven't initialized the replica set yet. When MongoDB runs in this mode without a configured set, it restricts external connections to only allow local clients to set up the replica set. That's exactly why your cross-node connections are accepted then immediately terminated.
Step-by-Step Fix: Initialize the Replica Set
Connect to one node locally (let's use machine A for this example):
mongo --host 10.20.106.12:27017Initialize the replica set with this JavaScript command in the mongo shell:
rs.initiate({ _id: "rs1", members: [ { _id: 0, host: "10.20.106.12:27017" }, { _id: 1, host: "10.1.0.192:27017" } ] })Wait 10-15 seconds for the set to sync, then check the status to confirm:
rs.status()You should see machine A marked as
PRIMARYand machine B asSECONDARY(orSTARTUP2briefly while it syncs initial data).Test cross-node connections:
- From machine B, run
mongo --host 10.20.106.12:27017 - From machine A, run
mongo --host 10.1.0.192:27017
Both should now connect successfully without dropping immediately.
- From machine B, run
Additional Checks (If the Above Doesn't Work)
- No hidden auth settings: Double-check that auth isn't accidentally enabled. Run this in the mongo shell to confirm:
Ensure there's nodb.getSiblingDB("admin").runCommand({getCmdLineOpts: 1})--authflag orauthorization: enabledin the output. - Verbose logging for deeper issues: If connections still drop, restart mongod with
--logLevel verbose, retry the cross-node connection, and look for log lines that explain why the connection was closed (e.g., replica set configuration mismatches).
内容的提问来源于stack exchange,提问作者shadaï ALI

