1/3
SSH Tunnel Basics
+15 XP on completion
#SSH Tunnel Basics
After this lesson you'll know:
- what an SSH tunnel is
- how to reach a remote database
- Local Port Forwarding vs Remote Port Forwarding
#The Scenario
Your app runs on a server. The database also runs on the server — but only on localhost (port 5432). You want to connect from your machine using psql or a GUI.
Solution: An SSH tunnel forwards a port from your machine through the SSH connection to the server.
#The Basic Tunnel
ssh -L 5432:localhost:5432 user@server
# Now localhost:5432 (your machine) = localhost:5432 (server)
#When the DB runs in a Docker container
# Option A: Via the host port
# (if -p 5432:5432 was set in docker run)
ssh -L 5432:localhost:5432 user@server
# Option B: Direct to the container IP
CONTAINER_IP=$(docker inspect db | grep IPAddress | tail -1 | grep -oE '[0-9.]+')
ssh -L 5432:$CONTAINER_IP:5432 user@server
#Common Pitfall
# Commonly misunderstood:
# -L 5432:localhost:5432
# ^^^^^^^^^ the localhost refers to the SERVER, not your machine!
# To connect to a different host:
ssh -L 5432:db.internal.company.com:5432 user@server
# db.internal.company.com must be reachable from the server
#✋ Try it out
ssh -L 8080:localhost:80 user@your-server— tunnel a web server from the server to your machine- Open http://localhost:8080 — you see the page running on the server
- Tunnel a database:
ssh -L 5433:localhost:5432 user@serverand connect withpsql -h localhost -p 5433
#📌 Summary
- SSH -L forwards a local port through the SSH connection to the server
- 'localhost' in the target refers to the SERVER, not your machine
- Essential for secure database access and other services
← → to navigate