Forward remote port to local using ssh
If you did not hear about SSH tunneling before, you must check it out! The method is known as SSH Port Forwarding / SSH Tunneling / SSH Proxying. Usecases:
- Super secure connection to any port on a remote host/server like VOIP, DATABASES, personal/debug HTTP ports. Without exposing the port to the whole world. No brute-forcing, no DDoS, no Network overload.
- Fast connection to remote daemon processes (e.g.
mysqld
,dockerd
, etc) which are listening on local hostslocalhost/127.0.0.1
without need to searching how to configure host binding and setting0.0.0.0
, and restarting daemons.
Let me show you, it is easy as ABC:
Assume you have a remote host with IP rhost_ip
and a system user remote_user
which you can connect by ssh
via 22
port.
To test the connection use:
ssh remote_user@rhost_ip
if it works you will see a new bash interpreter in your terminal (e.g. bash
). Exit from it using Ctrl+D
Assume you need to connect from your local machine to port 8080
on the remote host. But you have no 8080
port opened/forwarded to public IP (rhost_ip
).
In this case, you can forward it over ssh
to same or another local port.
ssh -L 3000:localhost:8080 remote_user@rhost_ip
This will start SSH session and make forwarding which will be alive with the session.
Then just connect to localhost:3000
and it will give you response to remote host port 8080
.
Note:3000
port should not be already used (bound) onlocalhost
before running ssh command.
BTW: to check all opened ports on the local host use:
sudo netstat -tulpn
To check opened ports on the remote host, run it after connecting via SSH.
😎 This console-based method works for any ports. However the SSH is so cool and secure, that is integrated in a lot of Desktop software which connects to remote PORTS, e.g. all database agents like Mysql Workbench or pgAdmin. When you create new server connection there you just can select SSH Tunneling, and specify host like localhost, plus define user and ssh private key/password
⌛ 🔑 To save time and get unbrackable secrity we always recomment using KEYPAIR instead of typing password each time. To generate keypair (~/.ssh/id_rsa
+/.ssh/id_rsa)
use ssh-keygen, then to install private jey to remote host usessh-copy-id remote_user@rhost_ip
. Then connect and password will not be asked🥳