raw cheat sheet

SSH Tunnel Cheat Sheet

Robert Eisele

SSH tunnels are a fast, secure way to reach services that should not be exposed to the public internet (databases, admin panels, internal APIs, message brokers, …). You create an encrypted SSH connection to a server, and SSH forwards traffic between a port on one side and a destination on the other.

Local Port Forwarding (-L)

Goal: You want to connect from your local computer to a service that is reachable from machine (often only inside its network, or only on its own loopback).

Typical situation:

You (on your laptop) want to open your database GUI / browser / CLI locally and connect to something that lives behind machine:

Example: Open local port 1234 and forward it to host:9876 through machine:

ssh -L 1234:host:9876 root@machine -NnT

How it works

Common real-world uses

Reverse Port Forwarding (-R)

Goal: A process running on machine (or someone logged into it) needs to connect to a service running on your local computer—even though your computer is behind NAT/firewall and cannot be reached directly.

Typical situation:

A remote script / service / coworker on machine wants to reach a service on your laptop (e.g. a local dev server, webhook receiver, debug endpoint).

Example: Open port 1234 on machine that forwards back to your local 9876:

ssh -R 1234:localhost:9876 root@machine -NnT

How it works

Common real-world uses

Note: Often, the forwarded port on machine is bound to its localhost by default (depends on SSH server config). If you want it reachable from other machines, you may need:

SSH Tunnel to a Unix Domain Socket

Goal: You want to connect from your local computer to a service that listens on a Unix socket on machine (not on a TCP port).

Typical situation:

Your local client (DB tool, script) can only speak TCP but the service on machine is configured for socket-only local access (common for MySQL/MariaDB).

Example: Forward local TCP 1234 to the remote socket /var/run/mysql.sock on machine:

ssh -L 1234:/var/run/service.sock root@machine -NnT

Why this is useful

Example: Open a Local MySQL Port for a Remote DB

Forward local port 3307 to the MySQL instance on machine that listens on 127.0.0.1:3306:

ssh -L 3307:127.0.0.1:3306 root@machine -NnT

or that listens on /var/run/mysql.sock on machine:

ssh -L 1234:/var/run/mysql.sock root@machine -NnT

Now connect locally as if MySQL were on your computer:

mysql -h 127.0.0.1 -P 3307 -u youruser -p

Tip: Using 127.0.0.1 instead of localhost can prevent some clients from trying a local socket instead of TCP.

What the flags mean (-NnT) and why they matter

Useful additions:

Example with safety options:

ssh -L 3307:127.0.0.1:3306 root@machine -NnT \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3

Quick mental model

Practical security notes