DEV Community

SS
SS

Posted on

Mastering SSH Reverse Tunneling: Access Local Services Anywhere

The Power of Reverse Tunnels

Ever tried to access a service running on your local machine from outside your network, only to be blocked by firewalls, NAT, or dynamic IPs? Usually, you'd reach for complex port forwarding. However, there is a much cleaner way: SSH Reverse Tunneling.

Instead of opening ports inward, you initiate an outbound connection from your restricted machine to a server that is publicly reachable. The traffic flows out through that established connection and back down into your local system.

Blog Image

How It Works

At its core, reverse tunneling uses the -R flag in your SSH command. This instructs your SSH client to ask the remote server to listen on a specific port and forward any incoming traffic received on that port back to your local environment.

The Basic Syntax:

ssh -R [remote-port]:localhost:[local-port] [user]@[remote-host]

  • [remote-port]: The port opened on the public server.
  • [local-port]: The port your service is running on locally.

Blog Image

Practical Use Cases

SSH reverse tunneling is a Swiss Army knife for developers and sysadmins:

  • Remote Webhooks: Test webhooks on localhost by exposing your local development server to the internet temporarily.
  • Remote Device Management: Control IoT devices (like a Raspberry Pi) sitting behind a home router without configuring the router itself.
  • Database Access: Query a local database from a remote machine without opening your database to the entire web.

Blog Image

Pro-Tips & Best Practices

  • GatewayPorts: If you want your remote server to forward traffic from outside its own local interface, ensure GatewayPorts yes is set in your remote /etc/ssh/sshd_config.
  • Keep It Persistent: Using ssh alone can time out. Tools like autossh are essential for production-grade setups to ensure the tunnel reconnects automatically if dropped.
  • Security First: Always use SSH keys instead of passwords. If you don't need a static host, consider using a managed service to handle the public-facing infrastructure for you.

Simplifying the Flow with Pinggy

Managing your own public SSH server for tunneling can be a hassle. Pinggy simplifies this by providing the infrastructure, so you don't have to worry about configs or VPS management. You can get a public URL for your local service with a single command:

ssh -p 443 -R0:localhost:3000 free.pinggy.io

This gives you a public URL that tunnels directly to your machine, bypassing the need for complex firewall rules entirely.

Read more about this from Pinggy Blog

Top comments (0)