How to connect mongodb server via ssh tunnel ?

An SSH tunnel (also called a Secure Shell tunnel) is a method of securely forwarding network traffic through an encrypted connection. It allows you to establish a secure connection to another computer over an insecure network. For example, the internet.

To connect to a MongoDB server running on a remote machine, you could use an SSH tunnel to forward a local port on your machine to the MongoDB port on the remote server. This would encrypt all traffic between your machine and the MongoDB server, providing a secure connection.

The command to construct a tunnel and connect to the MongoDB server is listed below.

ssh -fN -l username -i ~/path/to/id_rsa -L 3000:localhost:27017 hosted_mongodb_server_host_ip
A description of the ssh configuration options used above :

-f -> Requests ssh to go to background just before command execution.  This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in background.

-N -> Do not execute a remote command.  This is useful for just forwarding ports.

-l -> Specifies the user to log in as on the remote machine.

-i -> Selects a file from which the identity (private key) for public key authentication is read.

-L -> Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side.

You can connect to MongoDB via ssh tunnel using localhost IP and port 3000 once the tunnel has been established.

Once you’ve finished working with the MongoDB server, you can close the SSH connection by typing “exit” in the terminal.

Leave a Comment

Your email address will not be published. Required fields are marked *