How to use an SSH tunnel to forward ports

Security is important. Bastion hosts (or jump servers) are an easy way to wall
off your private servers from the outside world. Improved security is always a
good thing, but it isn’t always convenient.

With a bastion host in place, you shouldn’t be able to connect directly to a
private resource, like a database server. To connect to a private resource, you
can log into the bastion host, and then connect to the private resource from
there.

This works well enough, but in a situation when you want to run code on your
local machine, and connect to the private resource, this just won’t do.

In that scenario, you can use ssh to forward a port on your local machine to a
port on the private server, while routing things through the bastion host to
make it all work.

To make this happen, you’ll need to tell ssh a handful of things:

  • the port on our local machine to forward
  • the private resource we’re trying to connect to
  • the port on the private resource we’re trying to connect to
  • the username, port and host for our bastion host
  • to simply forward and not execute any remote command

To put all of those words in action, will look something like this:

ssh -N -L LOCALPORT:REMOTESERVER:REMOTEPORT BASTIONUSER@BASTIONHOST

Let’s say we were trying to forward local port 3333 to port 3306 on an RDS MySQL
server by way of a bastion host:

ssh -N -L 3333:mydb.us-east-1.rds.amazonaws.com:3306 user@bastion

At this point, if you were to connect to port 3333 on your localhost or
127.0.0.1 you would actually be connecting to port 3306 on your MySQL
server.

If you aren’t running MySQL locally, you could swap out 3333 for 3306 and
use the same port number locally and on the remote server.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.