Connect local port to server port
An SSH tunnel creates a connection between a port on your local machine and a address + port on the server, and tunnels the data to the server over SSH on port 22 to the server address + port.
This is done so that it doesn't get blocked by any firewalls or security groups (assuming only SSH connections are allowed to the server). After the data reaches the SSH server it gets forwarded to the address + port you specified when you created the SSH tunnel.
An important detail here is that the destination address + port are accessed from the context of the server, so localhost or 127.0.0.1 refer to the server machine on the destination side of the tunnel, not your local machine.
To create a SSH tunnel from local port to address + port on a server we would have to run the following command
ssh -i <private_key_pem> -N -f -L <local_port>:<address>:<port> <user>@<server_address>
Here,
-
<private_key_pem>is the path to the private key fileThis PEM file is used to connect to the server. It is the same private key file used to connect to the server using SSH
-
<local_port>is the local port to use as tunnel frontConnections made to this port on the local machine will be tunnelled to the server
address + port -
<address>is the address to tunnel to on the server -
<port>is the port to tunnel to on the server -
<user>and<server_address>are used to connect to the serverHere,
<user>is the username likeubuntu|ec2-user, and<server_address>is the actual address of the server like14.234.187.105 -
-Ninstructs SSH not execute a remote command, so it won't open a remote shell on the server. -
-finstructs SSH to run in the background.
To tunnel local port 8000 to MongoDB server instance running on our server(14.234.187.105) at 127.0.0.1:27017 we would have to run the following command. (Assuming private key for SSHing to our server is present in ~/.ssh/aws-key.pem on local machine)
ssh -i ~/.ssh/aws-key.pem -N -f -L 8000:127.0.0.1:27017 [email protected]
To close an SSH tunnel that is open in the background you can kill the background process with the following command
kill -9 <process id>
Run this command to find out the id of the processes concerning SSH ps aux | grep ssh
Then look for the line similar to the following line. This line is concerning our just created SSH tunnel
rituraj 12807 ... ssh -i /home...key.pem -N -f -L 8000:1...17 [email protected]
Here, 12807 is the PID or the process id for our SSH tunnel. You can close the tunnel by running
kill -9 12807