DEV Community

Cover image for Short snippets: SSH Port Forwarding
Victor Chan
Victor Chan

Posted on

1

Short snippets: SSH Port Forwarding

How to access a database behind a firewall

Scenario: Say you have a remote linux server somewhere remote (AWS EC2 or something) and you want to access a database whose port is blocked by a firewall, you can use the SSH (Secure Shell) local port forwarding command (-L) to gain access on your localhost to that port.

This is very useful when you’re developing and don’t want to expose your database in the cloud to the outside world.

Open a terminal and use this command below:

(You may be prompted to enter the user’s password for the remote server)

#This would connect you to port 5432 on your remote server
#And allow you to access it locally on port 5432 also, like magic!

$ ssh -L localhost:5432:localhost:5432 <user>@<server_ip>
Enter fullscreen mode Exit fullscreen mode

You can even specify another port if you wish, like this:

#This would connect you to port 5432 on your remote server
#And allow you to access it locally on port 8000

$ ssh -L localhost:8000:localhost:5432 <user>@<server_ip>

#You will notice that this creates a new shell
#(You will be logged in to your remote server)
#If you don't want this to happen then you can use the -N flag

$ ssh -NL localhost:8000:localhost:5432 <user>@<server_ip>
Enter fullscreen mode Exit fullscreen mode

Further Reading:

If you want to find out more about SSH and tunnels, I recommend the two links below, there are much more things you can achieve with SSH tunneling.

SSH Tunneling
How to create SSH Tunnels

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more