Scenario: You have an application running on a remote server, such as MySQL.
The server contains sensitive data so you lock it down behind a firewall such that only servers inside the local network can access this MySQL instance. You create a cloud network on "192.168.1.0". Basically only an IP of this range: "192.168.1.x" should be able to access MySQL on port 3306.
So how to access this MySQL instance from your dev machine?
Easy-peasy, just use SSH tunnels. Think of a tunnel as a private, encrypted pipeline that connects you to the remote server, allowing you access to just about anything on the remote server as if you were physically sitting in front of that machine with a keyword and a mouse.
π‘ An alternative approach is to use a VPN and just grant access to the VPN's IP.
Since you have an open tunnel, you essentially can access ports on the remote server as if they are running on your local machine via "127.0.0.1" or "localhost".
The firewall grants you access through SSH (usually port 22), thus the private network rule for "192.168.x.x" will not apply to you since you are essentially now on that server as "127.0.0.1".
Opening a tunnel
Okay great! Now that we understand conceptually what a tunnel is, let's open one:
autossh -L 3306:127.0.0.1:3306 -N me@my_remote_servers_ip
The "-L" flag will map port "3306" on the remote server to your local port "3306". Your local port doesn't have to be the same as the remote, you could for example use "3307" so that it doesn't clash with your local MySQL server.
Basically, the port on the left is your local port and the one on the right is the remote server's port.
The "-N" flag will prevent the SSH session from opening a terminal on the remote server. Without this flag, the port will still be mapped correctly, however, it'll also open a remote terminal just as if you started a regular SSH session.
Voila! Now you should be able to connect to the remote server's MySQL by connecting to host "127.0.0.1" and port "3306".
π‘AutoSSH is a drop-in replacement for SSH. Literally, just replace the word "ssh" with "autossh" in any "ssh" command, and it should work more or less the same way. The only difference is that AutoSSH will automatically reconnect your SSH session if it is disconnected ( a blip in your WIFI connection or network drop of some kind). On Ubuntu: "apt install autossh".
Top comments (0)