Connect to MongoDB by Using a SOCKS5 Proxy
On this page
Overview
In this guide, you can learn how to connect to MongoDB by using a SOCKS5 proxy. SOCKS5 is a standardized protocol for communicating with network services through a proxy server.
Tip
To learn more about the SOCKS5 protocol, see the Wikipedia entry on SOCKS.
SOCKS5 Proxy Settings
The proxy settings specify the SOCKS5 proxy server address and your authentication credentials. You can specify your settings in an instance of MongoClientSettings or in your connection string.
Important
The driver ignores the proxy settings if either of the following are true:
A Unix domain socket handles the communication. For more information, see the UnixServerAddress documentation.
TransportSettings
are configured. For more information, see the TransportSettings documentation.
The following table describes the SOCKS5 client options:
Name | Accepted Values | Description |
---|---|---|
proxyHost | String | Specifies the SOCKS5 proxy IPv4 address, IPv6 address, or hostname. You must provide this value to connect to a SOCKS5 proxy. |
proxyPort | non-negative Integer | Specifies the TCP port number of the SOCKS5 proxy server. This option
defaults to |
proxyUsername | String | Specifies the username for authentication to the SOCKS5 proxy server.
The driver ignores |
proxyPassword | String | Specifies the password for authentication to the SOCKS5 proxy server.
The driver ignores |
Examples
The following examples show how to instantiate a MongoClient
that connects
to MongoDB by using a SOCKS5 proxy. The proxy settings can be specified in a
MongoClientSettings
instance or a connection string. These examples use
the placeholder values described in the SOCKS5 Proxy Settings section.
Replace the placeholders with your proxy settings.
Specify Proxy Settings in the MongoClientSettings
The following code example shows how to specify your SOCKS5 proxy settings by
using the MongoClientSettings
builder:
MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyConnectionString( new ConnectionString("mongodb+srv://myDatabaseUser:myPassword@example.org/")) .applyToSocketSettings(builder -> builder.applyToProxySettings(proxyBuilder -> proxyBuilder .host("<proxyHost>") .port(<proxyPort>) .username("<proxyUsername>") .password("<proxyPassword>") ) ).build());
Specify Proxy Settings in the Connection String
The following code example shows how to specify your SOCKS5 proxy settings in your connection string:
String connectionString = "mongodb+srv://myDatabaseUser:myPassword@example.org/" + "?proxyHost=<proxyHost>" + "&proxyPort=<proxyPort>" + "&proxyUsername=<proxyUsername>" + "&proxyPassword=<proxyPassword>"; MongoClient mongoClient = MongoClients.create(connectionString);
API Documentation
To learn more about the methods and types discussed in this guide, see the following API documentation: