Skip to content

SSH tunnels: reach what only the server can see

NinjaLesson 62 of 669 min

Reach a service that only listens on the server, or a database only one machine may talk to, with an ssh tunnel: ssh -L, -N and -f, in a practice terminal.

Some things on a server are meant to be reached only from the server itself. The shop's app on web listens on 127.0.0.1:3000, so only programs on web can talk to it, and nginx passes it the requests it should see. The database on db is stricter still: its firewall lets in only web. That's good security, and a nuisance when you need to look at either from your laptop.

An ssh tunnel borrows your ssh login to carry one port across. (web and db are pretend machines in this page; the tunnels work the same way on real ones.)

ssh -L

ssh -L 3000:localhost:3000 web

reads as: listen on my port 3000, and send whatever arrives there through the ssh connection to web, which passes it on to localhost:3000 as seen from web. The middle part is looked up on the far side, so localhost there means web itself.

That also means you can reach a third machine through the one you ssh into:

ssh -L 5433:db:5432 web

Your port 5433 now leads, through web, to PostgreSQL on db, and db's firewall sees a connection from web, which it allows. A local port that's different from the far one (5433 here) avoids clashing with anything already on your own 5432.

Keep the terminal: -N and -f

Plain ssh -L … web also logs you in, and the tunnel lasts as long as that session. Usually you only want the tunnel:

OptionDoes
-Ndon't run a command or open a shell: just forward
-fgo to the background once connected

So ssh -f -N -L 3000:localhost:3000 web opens the tunnel and gives you your prompt back. ss -tlnp shows ssh listening on your port; kill it (find it with ps aux | grep ssh) to close the tunnel.

Tip:-R is the same idea backwards (a port on the server leads to your machine), and -D makes a SOCKS proxy. The practice ssh has -L only.

Your turn

Reach the app on web, which only listens on web itself, at http://localhost:3000/api/health from your laptop. Then forward your laptop’s port 5433 to PostgreSQL (port 5432) on db, through web.

Next