4

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.

Martin Prikryl
205k64 gold badges561 silver badges1.1k bronze badges
asked Aug 21, 2014 at 14:18
1

1 Answer 1

2

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;
  1. Check the host and port of the remote host and map it accordingly.
  2. Set the local port to what you are listening in the code (27020).

Try the whole exercise without code first maybe:

  1. Tunnel the remote MongodDB server using PuTTY (or command line if you are on Linux).
  2. Connect via Mongo to the local port where you mapped the remote port.
Martin Prikryl
205k64 gold badges561 silver badges1.1k bronze badges
answered Aug 23, 2014 at 7:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.