How to connect MongoDB Compass via ssh tunnel
If you’re doing a proper job (except it not being a replica set…), your instance is probably not listening to broadcast,your machine is behind a firewall and mongodb authentication is enabled . Because you don’t want all your data encrypted and being subjected to a handsome amount of BTC or XMR by some ransomware. So When you want to connect to your instance from your workstation anywhere , ssh tunnelling is the way to go.
To use SSH Tunnel While creating a connection on MongoDB Compass , you need to choose it from the drop down box for the other text boxes to show up.
The upcoming fields are pretty standard SSH information , nothing specific for MongoDB.
- SSH HostName can possibly be any FQDN , eg. Public IP address of the machine your instance is running on , or some sort of lengthy public URI you’re given by a cloud hosted machine.
- You might need to change the SSH Tunnel port if the SSH server on your database server machine is configured to use something other than the default 22
- SSH username is the user you want to log in , in that database server machine. And you need to select your private key as the identity file.
Fortunately, If you have a problem at this step , Compass helps you with a pretty clear error message , saying “Could not create SSH Tunnel” . So that you wouldn’t keep tweaking other settings instead.
The upper half of the Connection Settings page contains information about the MongoDB instace and the authentication.
For the Hostname and Port , you should be entering the values you set up for your instance , which is localhost and 27017 for default setups. Here in my example screen capture , the Hostname is 192.168.3.8 and the port is 37017. And after filling out the username and password for the MongoDB instance , your screen should look like below.
NOTE:(Please forgive me messing up by taking a screenshot as port 37017 and filling out the final image for 39017 … )
What’s beautiful is that , you just save all these settings as a favourite connection , and next time , connect to your safe&secure MongoDB instance with a simple click !
BONUS CONTENT : For using ssh tunnel for something other than mongodb compass , you can run the command below and connect to your remote mongodb instance as if you’re running it on your own machine.But you will need to authenticate explicitly in your code :)