2

I have setup my mongod.conf as follows so it only allows localhost connection.

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1

I then want my site to ssh into the mongodb so the port has to be converted to localhost.

However how can I integrate this with mongoose's connect function?

mongoose.connect(configDB.url, function(err){
  if (err){
    console.log('Error connecting to mongodb: ' + err)
  }
});

I have found the following command but I am not sure if this is what I need:

ssh -L 4321:localhost:27017 -i ~/.ssh/ssh_key user@ip-adress

This should ssh me via port 4321 to the localhost right? So I think I need something like this in the nodejs mongoose's connect function. I've tried to read up on this on the mongodb security tutorials but I cannot link their instructions to nodejs at all. Anyone who has experience with this?

2 Answers 2

6

You're nearly there. Set up the tunnel independent of node:

ssh -Nf -p [db_server_ssh_port] [mongo_user]@[mongo_domain] -L \
[local_db_port]:localhost:[remote_db_port]

And then within node, connect to mongo using [local_db_port]:

mongoose.connect(
  "mongodb://localhost:[local_db_port]/[db_name]",
  {"pass":"[db_pwd]"}
)

All the traffic sent to [local_db_port] on the web server will be sent through the tunnel to port [remote_db_port] on [mongo_domain]. The following post gives more info. It's connecting to a MySQL database, but the principle is the same.

Connect to MySQL using SSH Tunneling in node-mysql

Sign up to request clarification or add additional context in comments.

Comments

2

Set up the tunnel independent of node:

ssh -L [your given port]:localhost:27017 [username of ssh]@[ip address of ssh matchine] -f -N

after that you have include your given port for mongo database. In the nodejs you have to setup for mongoose connection like this

'mongodb://localhost:[your given port number]/[database name]'

enjoy it

1 Comment

Awesome! Great answer!

Your Answer

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.