Connection Troubleshooting
On this page
- Server Connection Errors
- Check the Connection String
- Configure the Firewall
- Check the Number of Connections
- Authentication Errors
- Check the Credentials Formatting
- Verify the Authentication Mechanism
- Verify User Is in Authentication Database
- DNS Resolution Errors
- Check Database Deployment Availability
- Check the Network Addresses
- Security Certificate Errors
- Timeout Errors
- Set
maxConnectionTimeoutMS
- Set
maxConnectionLifeTime
andmaxConnectionIdleTime
- Server Selection Timeout Exceptions
- Miscellaneous Errors
- Monitor Thread Exception
- Certificate Request Exception
- Debugging Tips
- Verbose Logging for TLS/SSL
This page offers potential solutions to issues that you might encounter when using the MongoDB Java Driver to connect to a MongoDB deployment.
Note
This page addresses only connection issues. If you encounter other issues when using MongoDB or the driver, visit the following resources:
The Issues & Help page for information about reporting bugs, contributing to the driver, and finding more resources
The MongoDB Community Forums for questions, discussions, or general technical support
The Frequently Asked Questions (FAQ) page for answers to common questions about the Java driver
Server Connection Errors
When an issue occurs when you attempt to connect to a server, the Java driver returns an error message. If this error resembles the following message, it indicates that the driver cannot connect to a MongoDB deployment:
Error: couldn't connect to server 127.0.0.1:27017
The following sections describe methods that might help resolve the issue.
Check the Connection String
Verify that the hostname and port number in the connection string are both
accurate. In the sample error message, the hostname is 127.0.0.1
and the
port is 27017
. The default port value for an instance of MongoDB Server is
27017
, but you can configure MongoDB to listen on another port.
When connecting to a replica set, include all the replica set hosts in your connection string. Separate each of the hosts in the connection string with a comma. This enables the driver to establish a connection if one of the hosts is unreachable.
To learn how to specify multiple replica set hosts, see the Connect to a Replica Set section of the Connection Guide.
Configure the Firewall
If your MongoDB deployment is hosted behind a firewall, ensure the port
on which MongoDB listens is open in the firewall. If your deployment
listens on the default network port, ensure that port 27017
is
open in the firewall. If your deployment listens on a different port,
ensure that port is open on the firewall.
Warning
Do not open a firewall port unless you are sure that it is the one that your MongoDB deployment listens on.
Check the Number of Connections
Each MongoClient
instance supports a maximum number of concurrent open
connections in its connection pool. The configuration parameter maxPoolSize
defines this value and is set to 100
by default. If the
number of open connections is equal to maxPoolSize
, the server waits until
a connection becomes available. If this wait time exceeds the maxIdleTimeMS
value, the driver responds with an error.
To learn more about how connection pooling works in the driver, see How Does Connection Pooling Work in the Java Driver? in the FAQ.
Authentication Errors
The Java driver may be unable connect to a MongoDB deployment if the authorization is not configured correctly. In these cases, the driver raises an error message similar to the following message:
Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017.
The following sections describe methods that may help resolve the issue.
Check the Credentials Formatting
One of the most common causes of authentication issues is invalid credentials formatting in the MongoDB connection string.
Tip
For more information about using connection strings, see Connection URI in the Connection Guide.
If your connection string contains a username and password, ensure that they are correctly formatted.
Note
If your username or password includes any of the following characters, you must percent-encode it:
: / ? # [ ] @
Use your percent-encoded username and password in your connection string.
Verify the Authentication Mechanism
Ensure that your credentials and authentication mechanism are correct. You can specify your authentication credentials in the options of your connection string.
If you construct a client by using a MongoCredential
, the builder method
corresponds to the authentication mechanism. The following code shows the builder
method for the SCRAM-SHA-256
authentication mechanism:
MongoCredential credential = MongoCredential.createScramSha256Credential("<db_username>", "<authenticationDb>", "<dbpassword>");
To learn more about specifying authentication mechanisms, see the Authentication Mechanisms and Enterprise Authentication Mechanisms guides.
Verify User Is in Authentication Database
When using a username and password-based authentication method, the username must be defined in the authentication database.
The default authentication database is the admin
database.
To use a different database for authentication, specify the
authSource
option in the connection string.
The following example instructs MongoDB to use the users
database
as the authentication database:
MongoClient mongoClient = MongoClients.create("mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=users");
DNS Resolution Errors
The Java driver may be unable to resolve your DNS connection. When this happens, you might receive an error message similar to the following message:
com.mongodb.MongoSocketWriteException: Exception sending message
If the driver reports this error, try the methods in the following sections to resolve the issue.
Check Database Deployment Availability
If you are connecting to MongoDB Atlas and your driver cannot find the DNS host of the Atlas database deployment, the database deployment might be paused or deleted.
Ensure that the database deployment exists in Atlas. If the cluster is paused, you can resume the cluster in the Atlas UI or the Atlas command line interface.
To learn how to resume a cluster, see Resume One Cluster in the Atlas documentation.
Check the Network Addresses
Verify that the network addresses or hostnames in your connection string are accurate.
If your deployment is hosted on MongoDB Atlas, you can follow the Connect to Your Cluster tutorial to find your Atlas connection string.
Security Certificate Errors
If you use Java version 8 or earlier, you might need to add a certificate to your trust store. You can either upgrade to a later version of the JDK or read the Security FAQ instructions in the Atlas documentation for information on how to add the certificate.
Timeout Errors
When you send messages through the driver to the server, sometimes the messages take a while to respond. When this happens, you might receive an error message similar to one of the following messages:
Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}.
No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description
If you receive one of these errors, try the following methods to resolve the issue.
Set maxConnectionTimeoutMS
The maxConnectionTimeoutMS
option indicates the time the Java driver waits
for a connection before timing out. The default value is 10000
. You can
increase this value or set it to 0
if you want the driver to never timeout.
Set maxConnectionLifeTime
and maxConnectionIdleTime
Consider setting maxConnectionLifeTime
and
maxConnectionIdleTime
. These parameters configure how long the driver
maintains a connection to a MongoDB instance. For more information about these
parameters, see Connection Pool Settings.
Server Selection Timeout Exceptions
Your application might not be able to complete a request even when some servers are available, causing the driver to return a server selection timeout exception.
This exception is of type MongoTimeoutException
. The following
shows a sample of the exception that occurs if you attempt to send a
request to a replica set in which the primary is not reachable:
com.mongodb.MongoTimeoutException: Timed out while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[ {address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}, {address=localhost:27019, type=REPLICA_SET_SECONDARY, roundTripTime=15.0 ms, state=CONNECTED} ] }
The error includes a view of the cluster state that describes the connection state of each node, which can help you identify the source of your connection issue.
In the preceding error, the only connected server, localhost:27019
,
is a secondary node. Because of this, the request times out as the
driver is unable to select a server that satisfies the read preference
of primary
. In this situation, you can still perform read operations
against the connected secondary node if you set the read preference to
secondary
, secondaryPreferred
, or nearest
.
You can also specify the serverSelectionTimeoutMS
connection option
to adjust the amount of time in which the driver must select a server. To
learn more, see the Connection Options guide.
Miscellaneous Errors
This section shows connection errors that do not fall into a broader category.
Monitor Thread Exception
INFO: Exception in monitor thread while connecting to server ssc-cluster-01-shard-00-02.9cbnp.mongodb.net:27017
This log line indicates that the monitor that continuously
checks the status of each replica set member or mongos
server failed to
contact one of the nodes or servers. This is an expected message during server
maintenance operations and can be safely ignored.
Certificate Request Exception
javax.net.ssl.SSLHandshakeException: extension (5) should not be presented in certificate_request
This is a known issue in certain versions of the JDK that can occur when attempting to connect by using the TLS 1.3 protocol.
If you encounter this error when connecting to your MongoDB instance or cluster, update your JDK to one of the following patch versions or newer:
JDK 11.0.7
JDK 13.0.3
JDK 14.0.2
To learn more about this issue, see the issue description in the OpenJDK Bug system tracker issue.
Debugging Tips
While not related to a specific error message, this section includes information that can help in the process of troubleshooting connection issues.
Verbose Logging for TLS/SSL
You can use the -Djavax.net.debug=all
system property to enable
debug-level logging related to all connections, including those
established by using TLS/SSL.
Enabling debug-level logging can help you diagnose the root problem of connection issues. To learn more about the TLS/SSL logging messages, see the Debugging SSL/TLS Connections Java documentation.