Port Forward to remote server on virtual private cloud using SSH

Considering you have a service running in VPC but it cannot be accessible over the internet and only accessible from the VPC. To access other services that are blocked over the internet, you can use SSH to connect to any one of the server in VPC that is accessible and forward to port to the destination service as follows

ssh -L [bindaddr]<port>: <destination-server>:<destination-port> <server>

Where,

bindaddrLocal Address to bind
portLocal port to bind
destination-serverDestination service IP
destionation-portDestination port of service
serverServer to connect

Option -L specifies the given port on the local (client) host is to be forwarded to the given host and port on the remote side. This works by allocating the socket to the specified local port and optionally binding it to the specified bindaddr. When connection is made to this location port specified, it is forwarded over the secure channel and connection is made to the specified “destination-server” and “destination-port” from the remote machine. If bindaddr is not specified, SSH listens on all interfaces.

If you are connecting to server with key file instead of password, use

ssh -i <keyfile> -L [bindaddr]<port>: <destination-server>:<destination-port> <server>

We can also use SSH to create the SOCKS proxy

ssh -D 1337 -q -C -N -f  use@server

Where,

-D Bind to local port given following by this option
-qQuite mode, don’t output anything
-CCompress the data
-NDo not execute any remote command, it is useful when forwarding ports
-fRun in background

..

exmaple:

ssh -L 6379:192.168.31.22:3033 root@servername.com 

Where SSH acts as the tunnel and forwards the requests destined to port 6379 on localhost to the specified port 3033 on host 192.168.31.22 on the remove network.

While -L option forwards connection on local specified port to remove host, it is also possible to configure SSH in such a way that connection on remove bound port to local host & port using option -R. This works by allocating a socket to listen to port on the remove host.

ssh -R [bind_address:]port:host:hostport 

The listening socket on the server will be bound to the 127.0.0.1 only by default, this can be changed by specifying bind_address. If bind_address is specified as ‘*’ or empty which indicates that socket should listen on all interfaces

Example

ssh -R 6379:192.168.31.25:3033 root@servername.com 
Default image
neotam
Naveen T aka neotam. Programming language agnostic, Software architect, Python expert, Networking & DevOps engineer & consultant with 7+ years of experience in creating serious web applications, real time event-driven non blocking applications and database driven applications ranging from small scale to enterprise grade. website
Leave a Reply