Forward a remote port to your computer with SSH
Use ssh -L to open a database, admin panel or debug server that runs on a remote server on your own localhost, without opening it to the internet.
Imagine a server with a door that only opens from the inside. Your database, admin panel or debug server is listening on a port behind it, and that port is closed to the internet. Good! Keep it closed.
SSH can dig a private tunnel to that door. You knock on the one door that is already open (SSH, port 22), and SSH carries your traffic through it.
ssh -N -L 8080:localhost:80 user@server_ip
Now open http://localhost:8080 on your computer, and you are talking to port 80 on the server.
How to read -L 8080:localhost:80:
8080is the port on your computer.localhost:80is the destination as the server sees it, solocalhosthere means the server itself.-Nmeans "only keep the tunnel, don't open a shell". Press Ctrl+C to close it.
Two everyday uses:
- Open a remote Postgres in your local database tool:
ssh -N -L 5433:localhost:5432 user@server_ip, then connect tolocalhost:5433. - Reach a service that only listens on the server's private network:
-L 9000:10.0.0.5:9000.
Things that trip people up:
- If the local port is already taken, SSH will complain. Pick another one.
- The tunnel only lasts as long as the SSH connection. Close the terminal and it's gone.
- By default the tunnel listens only on your own machine, which is what you want. Other people on your Wi-Fi can't use it.
There is also the opposite direction, -R, which makes a port on your computer reachable from the server. Use it rarely and carefully.
In short: keep private ports closed, and use ssh -L to borrow them for yourself when you need them.
Get your project quote
Free result within 48-72 hours
Related insights
Blocking vs asynchronous code, explained simply
Blocking code stands and waits, async code works on something else in the meantime. Why that matters, and why neither one fixes a slow query.
Install PostgreSQL and create a database and user from the command line
Install PostgreSQL on Ubuntu or WSL, then create a database owned by its own user in two SQL commands, and connect with one URL.
How to create an AWS account and keep it safe
Create an AWS account the safe way. Protect the root user with MFA, set a budget alert and use a separate short-lived login for daily work.