Connection Troubleshooting
Diagnose and fix common MongoDB connection issues including DNS, firewall, authentication, and timeout problems
Connection Troubleshooting
Diagnose and resolve common MongoDB connection issues. This guide covers connection failures, authentication errors, network problems, and performance issues.
Connection Test Tool
MongoDash includes a built-in connection test to diagnose issues:
The test validates:
- DNS Resolution - Hostname resolves to IP address
- Network Connectivity - Can reach MongoDB port
- TLS/SSL Handshake - Encryption negotiation succeeds
- Authentication - Credentials are valid
- Authorization - User has required permissions
- Database Access - Can list databases and collections
The connection test provides specific error messages and recommendations for each failure. Always run the test before investigating manually.
Common Connection Errors
Connection Refused
Error Message:
Error: connect ECONNREFUSED 192.168.1.100:27017
MongoNetworkError: failed to connect to server
Causes:
- MongoDB service is not running
- Wrong host or port in connection string
- Firewall blocking connection
- MongoDB not listening on specified interface
Solutions:
Verify MongoDB is running
# Linux
sudo systemctl status mongod
# macOS
brew services list | grep mongodb
# Check process
ps aux | grep mongodCheck MongoDB is listening
# Verify MongoDB port is open
sudo netstat -tulpn | grep 27017
# Or use lsof
sudo lsof -i :27017Verify bind IP in MongoDB config
Check /etc/mongod.conf:
net:
port: 27017
bindIp: 0.0.0.0 # Listen on all interfacesRestart after changes: sudo systemctl restart mongod
Test connection locally
# From MongoDB server
mongo localhost:27017
# Or use telnet
telnet localhost 27017DNS Resolution Failure
Error Message:
Error: getaddrinfo ENOTFOUND cluster0.mongodb.net
MongoNetworkError: failed to resolve hostname
Causes:
- Incorrect hostname in connection string
- DNS server cannot resolve hostname
- Network configuration issues
- DNS propagation delay (new domains)
Solutions:
Verify hostname spelling
- Double-check connection string
- Ensure no extra spaces or typos
- Verify domain is correct
Test DNS resolution
# Test DNS lookup
nslookup cluster0.mongodb.net
# Or use dig
dig cluster0.mongodb.net
# Test from specific DNS server
nslookup cluster0.mongodb.net 8.8.8.8Check network DNS settings
- Verify DNS servers in network settings
- Try Google DNS (8.8.8.8, 8.8.4.4)
- Try Cloudflare DNS (1.1.1.1, 1.0.0.1)
Use IP address temporarily
- Resolve hostname manually
- Replace hostname with IP in connection string
- Example:
mongodb://192.168.1.100:27017/db - Note: Not recommended for production
For MongoDB Atlas SRV records, ensure your DNS resolver supports SRV lookups. Some corporate DNS servers block SRV queries.
Authentication Failed
Error Message:
MongoError: Authentication failed
Error: bad auth : authentication failed
Causes:
- Incorrect username or password
- Wrong authentication database
- User does not exist
- User lacks required privileges
Solutions:
Verify credentials
- Check username and password for typos
- Ensure no extra spaces
- Verify password special characters are URL-encoded
- Example:
password#123becomespassword%23123
Check authentication database
Add authSource=admin to connection string:
mongodb://user:pass@host:27017/db?authSource=adminCommon auth databases: admin, $external
Verify user exists
use admin
db.getUser("username")Check user permissions
use admin
db.getUser("username", { showPrivileges: true })Ensure user has required roles (e.g., read, readWrite)
Test credentials locally
mongo "mongodb://user:pass@host:27017/db?authSource=admin"Connection Timeout
Error Message:
MongoNetworkError: connection timeout
Error: Server selection timeout after 30000 ms
Causes:
- Firewall blocking connection
- Network routing issues
- MongoDB server overloaded
- Incorrect replica set configuration
- Geographic latency
Solutions:
Increase timeout values Add to connection string:
mongodb://host:27017/db?connectTimeoutMS=30000&serverSelectionTimeoutMS=30000Check firewall rules
# Test port connectivity
telnet host 27017
# Or use nc
nc -zv host 27017
# Test with timeout
timeout 5 bash -c "</dev/tcp/host/27017" && echo "Port open"Verify IP whitelisting
- Check MongoDB Atlas Network Access settings
- Ensure MongoDash IPs are whitelisted
- Temporarily add
0.0.0.0/0for testing (remove after)
Check MongoDB server load
db.serverStatus()
db.currentOp()High CPU or connections may cause timeouts
Test geographic latency
# Ping MongoDB host
ping -c 5 host
# Test latency with time
time mongo host:27017 --eval "db.serverStatus()"High latency (>500ms) may require timeout increases
TLS/SSL Errors
Error Message:
MongoNetworkError: SSL handshake failed
Error: unable to verify the first certificate
Error: self signed certificate in certificate chain
Causes:
- Self-signed certificate without CA
- Certificate validation failure
- Hostname mismatch
- Expired certificate
- Wrong TLS version
Solutions:
Verify TLS is enabled on MongoDB Check MongoDB config:
net:
tls:
mode: requireTLS
certificateKeyFile: /path/to/cert.pem
CAFile: /path/to/ca.pemUpload CA certificate to MongoDash
- For self-signed certificates, upload CA cert
- Navigate to Connection → TLS/SSL Settings
- Upload CA certificate file
Check certificate validity
# View certificate details
openssl s_client -connect host:27017 -showcerts
# Check expiration
echo | openssl s_client -connect host:27017 2>/dev/null | openssl x509 -noout -datesVerify hostname matches certificate
- Certificate CN or SAN must match hostname
- Use IP address if certificate is for IP
- Or use
tlsAllowInvalidHostnames=true(testing only)
Skip validation for testing Add to connection string (development only):
mongodb://host:27017/db?tls=true&tlsAllowInvalidCertificates=trueNever use tlsAllowInvalidCertificates=true in production. This disables critical security checks.
Replica Set Connection Issues
Error Message:
MongoNetworkError: replica set member is not a master
Error: no primary found in replica set
Error: replica set name mismatch
Causes:
- Incorrect replica set name
- Primary election in progress
- All members down
- Network split
Solutions:
Verify replica set name Check MongoDB replica set config:
rs.conf()Use exact name in connection string:
mongodb://host1,host2,host3/db?replicaSet=myReplicaSetCheck replica set status
rs.status()Verify:
- At least one PRIMARY member
- Members are reachable
- No recent elections
List all replica set members Include all members in connection string:
mongodb://host1:27017,host2:27017,host3:27017/db?replicaSet=rs0Check network connectivity between members
# From each member, ping other members
ping host1
ping host2
ping host3Wait for primary election
- Elections typically complete in seconds
- Check
rs.status()for state changes - Retry connection after election completes
Performance Issues
Slow Connection Establishment
Symptom: Connection takes 10+ seconds to establish
Causes:
- DNS resolution delays
- Geographic distance
- Connection pooling issues
- Network latency
Solutions:
Enable connection pooling
mongodb://host:27017/db?maxPoolSize=50&minPoolSize=10Use SRV records for Atlas
mongodb+srv://cluster.mongodb.net/dbSRV records provide faster connection discovery
Choose geographically closer region
- Use MongoDB Atlas region selector
- Deploy database near MongoDash region
- Consider multi-region deployment
Optimize DNS caching
- Configure longer DNS TTL
- Use local DNS caching resolver
- Pre-resolve hostnames
Query Timeouts
Symptom: Queries timeout but connection is stable
Causes:
- Missing indexes
- Large collection scans
- Complex aggregations
- Server overload
Solutions:
Increase operation timeout
mongodb://host:27017/db?socketTimeoutMS=60000Check query execution plan
db.collection.find({field: "value"}).explain("executionStats")Look for COLLSCAN (collection scan) instead of IXSCAN (index scan)
Add indexes for slow queries
db.collection.createIndex({field: 1})Monitor server performance
db.serverStatus()
db.currentOp()Check for high CPU, memory, or active operations
Diagnostic Commands
Useful commands for troubleshooting:
Network Testing
# Test TCP connection
telnet host 27017
nc -zv host 27017
# Test DNS resolution
nslookup host
dig host
# Test with MongoDB client
mongo "mongodb://host:27017/db"
# Check network route
traceroute host
mtr host
# Test latency
ping -c 10 host
MongoDB Server Diagnostics
// Server status
db.serverStatus()
// Database stats
db.stats()
// Current operations
db.currentOp()
// Connection stats
db.serverStatus().connections
// Replication info (replica sets)
rs.status()
rs.conf()
// Check user permissions
db.getUser("username", {showPrivileges: true})
Log Analysis
# MongoDB logs (Linux)
sudo tail -f /var/log/mongodb/mongod.log
# Search for errors
sudo grep -i error /var/log/mongodb/mongod.log
# Filter by date
sudo grep "2026-02-24" /var/log/mongodb/mongod.log
# Authentication failures
sudo grep -i "authentication failed" /var/log/mongodb/mongod.log
Firewall Configuration
Common firewall configurations for MongoDB access:
Linux (ufw)
# Allow MongoDB port
sudo ufw allow 27017/tcp
# Allow from specific IP
sudo ufw allow from 203.0.113.10 to any port 27017
# Check status
sudo ufw status
Linux (iptables)
# Allow MongoDB port
sudo iptables -A INPUT -p tcp --dport 27017 -j ACCEPT
# Allow from specific IP
sudo iptables -A INPUT -p tcp -s 203.0.113.10 --dport 27017 -j ACCEPT
# Save rules
sudo iptables-save > /etc/iptables/rules.v4
AWS Security Groups
- Navigate to EC2 → Security Groups
- Select MongoDB security group
- Add Inbound Rule:
- Type: Custom TCP
- Port: 27017
- Source: MongoDash IP or CIDR
MongoDB Atlas IP Whitelist
- Log into Atlas dashboard
- Navigate to Network Access
- Click Add IP Address
- Enter MongoDash static IPs or
0.0.0.0/0for testing
Using 0.0.0.0/0 in Atlas Network Access allows connections from any IP address. Only use for testing and remove immediately after.
Error Code Reference
Common MongoDB error codes and meanings:
| Code | Error | Cause |
|---|---|---|
| 13 | Unauthorized | Authentication failed or insufficient permissions |
| 18 | AuthenticationFailed | Invalid credentials or auth database |
| 24 | LockTimeout | Operation timed out waiting for lock |
| 50 | MaxTimeMSExpired | Query exceeded time limit |
| 89 | NetworkTimeout | Network operation timeout |
| 6 | HostUnreachable | Cannot reach MongoDB host |
| 11600 | InterruptedAtShutdown | MongoDB is shutting down |
| 13436 | ReplicaSetNotFound | Replica set name mismatch |
Getting Help
If you cannot resolve connection issues:
Gather diagnostic information
- Connection string (redact password)
- Error messages
- Connection test results
- MongoDB logs
- Network configuration
Check documentation
- Review connection type guide
- Check SSH tunnel setup
- Verify security configuration
Contact support
- Email: support@mongodash.com
- Include diagnostic information
- Provide reproduction steps
When contacting support, include the connection test results and any error codes. This helps us diagnose issues faster.