To connect to MongoDB from Java I use:
MongoClient mongoClient = new MongoClient("localhost", port);
And it works fine. Now I would like to connect to MongoDB which is on machine where I have to login by SSH. I try to use JSch for this, here is my code:
String host = "host";
String user = "user";
String password = "pass";
int port = 22;
int tunnelLocalPort = 3309;
String tunnelRemoteHost = "host";
int tunnelRemotePort = 3306;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
localUserInfo lui = new localUserInfo();
session.setUserInfo(lui);
session.connect();
session.setPortForwardingL(tunnelLocalPort, tunnelRemoteHost, tunnelRemotePort);
Everything looks fine, I can connect, but here is a problem:
MongoClient mongoClient = new MongoClient("localhost", 27020);
List<String> databaseNames = mongoClient.getDatabaseNames();
LOG.info("DB names=" + databaseNames);
And error is:
Aug 21, 2014 4:12:29 PM com.mongodb.DBTCPConnector initDirectConnection
Warnung: Exception executing isMaster command on localhost/127.0.0.1:27020
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27020] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
Should I set something more to connect? How can I check from Java that program connects, when I check session.isConnected() output is true. When I use PuTTY everything works fine.
-
See also Connecting to mongo database through SSH tunnel in Java.Martin Prikryl– Martin Prikryl2020年05月14日 11:07:11 +00:00Commented May 14, 2020 at 11:07
1 Answer 1
From above code I think you are tunneling a remote 3309 port to a local port on 3309 (and not 27020).
Per your code:
int tunnelLocalPort = 3309; String tunnelRemoteHost = "host"; int tunnelRemotePort = 3306;
- Check the host and port of the remote host and map it accordingly.
- Set the local port to what you are listening in the code (27020).
Try the whole exercise without code first maybe:
- Tunnel the remote MongodDB server using PuTTY (or command line if you are on Linux).
- Connect via Mongo to the local port where you mapped the remote port.