Ubuntu – How to connect to remote mongoDB via ssh (via Sacred)? connection refused

mongodbsshssh-tunnelUbuntu

I have two computers: Ubuntu1 and Ubuntu2.
Ubuntu1 runs MongoDB with database Sacred3.
I want to run connect from U2 to U1 via ssh and store there my experiment results.

What I tried and failed:
1. I installed mongo DB, created sacred3, I have ssh key to it.
I edited /etc/mongod.conf adding:

# network interfaces
net:
port: 27017
bindIp: 0.0.0.0

Then I enabled port forwarding with

ssh -fN -i ~/.ssh/sacred_key-pair.pem -L 6666:localhost:27017 ubuntu@106.969.696.969 // (with proper ip)

so, as I undertstand, if I connect to my localhost:6666 it will be forwarded to 106.969.696.969:27017

So after that, I'm runnig an experiment with Sacred framework:

python exp1.py -m localhost:6666:sacred3

and this should write experiment to remote DB, HOWEVER i I get:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

which is driving me mad. please help!

Best Answer

Your error says pymongo is looking for mongod on localhost:27017

pymongo.errors.ServerSelectionTimeoutError: localhost:27017

But it isn't there, you've forwarded it to localhost:6666. The connection string in your code must have a hardcoded default you'll need to edit.

Or, if nothing is running on localhost:27017 you can tunnel directly:

ssh -fN -i ~/.ssh/sacred_key-pair.pem -L 27017:localhost:27017 ubuntu@106.969.696.969

Other useful commands are

  • List ssh processes

ps aux | grep ssh

  • Which process is using a port (27107 in this case)

sudo netstat -lnpt | awk '$4 ~ /:27107/ {sub(/\/.*/, "", $7); print $7}'

  • Free up a port by killing the process using it

kill <pid>

Also bind to local host, using 0.0.0.0 is making mongodb available to anyone anywhere that can reach the server.

net:
  port: 27017
  bindIp: 127.0.0.1