Use SSH to expose local service (port) in the private network to a public server

Suppose you have a service(website) running on your local machine. Your machine is possibly in a private network. So, people on the Internet cannot access your service.

If you have SSH access to a public server, then you can expose your local service to the public server. After that, people on the Internet can access your service through the public server.

Configuration

On the public server, check /etc/ssh/sshd_config configuration file and make sure that GatewayPorts option is enabled.

GatewayPorts yes

Example command

Suppose your local service(website) is running on port 80 and the public server is called your-pub-server.com, execute the following command on your machine:

ssh -NTR 8888:localhost:80 user@your-pub-server.com
  • -NTR tells SSH to forward server request to local machine.
  • 8888:localhost:80 has three parts separated by colons. The 1st part is the port on the public server; The 2nd part is hostname of your local machine (typically localhost); The 3rd part is the local port.
  • user@your-pub-server.com at the end is the public server with username.

Now, when people access your-pub-server.com:8888, they are in fact accessing your local machine's port 80.

Posted on 2022-06-04