how to connect to mongodb server via ssh tunnel

The "channel 2" and "channel 3" lines are from ssh. The sshd instance on the remote server is trying to connect to port 27017 in order to service a tunnel connection, and it's getting a "connection timed out" error.

In other words, sshd on the remote server can't reach the target of the tunnel. Since the remote host is also the host which you're supposedly tunneling to, it's hard to say what the specific problem is. It could be that "" resolves to more than one IP address. You're making an SSH connection to one server in the cluster, and then a different server in the cluster is being chosen as the tunnel target. You could try changing the tunnel target to "localhost" instead of "":

ssh -fN -l root -i path/to/id_rsa -L 9999:localhost:27017


"-L 9999:localhost:27017" means that the ssh client on the local server listens for connections on port 9999. When it gets a connection, it tunnels the connection to the sshd instance on the remote server. The remote sshd instance connects from there to localhost:27017. So "localhost" here is from the perspective of the remote server.

With the netstat output, it's a little clearer why it wasn't working before. The " " part means that Mongodb is specifically bound to the localhost ( interface on the remote host. You can't contact that instance of mongodb directly by trying to connect to the host's regular IP address--you can only contact that instance of mongodb through the localhost address. And of course, since it's localhost, you can only contact if from a client running on the same host.

So, the way you're doing it now--tunnel a connection to the server through ssh and then connect to localhost from there--is the way to do it.