Tunnelling using SSH

What is a Tunnel

Well for those of you who are not familiar it’s exactly what it says it is. It’s a path from one place to another. You go in through one side and come out via the other. Great so why do we need it? Hmm!

With cloud providers like AWS and all, they have a separate firewall over the normal system firewall whereby you can’t access them directly . i.e. hit the port directly even though it is open. But what they do allow is accessing it via port forwarding via SSH.

So here is what we will do. We use SSH on port 22 and then forward our requests to the needed ports from there on.

The NestJs way of doing things

So here is what you need. You need this excellent package called Tunnel-ssh. Let’s install it –

npm install tunnel-ssh --save

What am trying to do

I have MongoDb running on port 27017 on an AWS EC2 instance. I want to access it from my local IDE. But AWS doesn’t allow me to directly hit the port like domain.com:27017. So I have to use SSH to do that.

const tunnel = require('tunnel-ssh');
const tunnelConfig = 
	username: '<your-username>',
	privateKey: require('fs').readFileSync('./aws.pem'),
	host: '<your-aws-ip>',
	port: 22,
	dstPort: 27017,
	localHost: '',
	localPort: 27017

tunnel(tunnelConfig, function (error, server){});

       MongooseModule.forRoot(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
export class RootModule { }

So here is what we did –

  1. We made a tunnel config which essentially says that forward whatever goes to localhost to my host and whatever goes to my localPort 27017 to my dstPort 27017.
  2. The above is possible because of the aws.pem file. You will get this file from AWS control panel. So all the communication happens via port 22 (SSH).

And that’s it. You can now connect your local IDE to the production’s database.

Happy Tunnelling!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.