Docs / Networking / Setting Up a Reverse SSH Tunnel

Setting Up a Reverse SSH Tunnel

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 32 views · 1 min read

The Scenario

You have a server behind a NAT or firewall that you cannot reach directly. A reverse SSH tunnel lets the remote server connect back to your accessible server, creating a tunnel you can use.

How It Works

# From the REMOTE (unreachable) server, connect to your PUBLIC server:
ssh -R 2222:localhost:22 user@public-server

This forwards port 2222 on your public server to port 22 on the remote server.

Access the Remote Server

# From the public server:
ssh -p 2222 localhost
# This connects to the remote server through the tunnel

Persistent Tunnel with autossh

sudo apt install -y autossh

# On the remote server
autossh -M 0 -f -N \
  -o "ServerAliveInterval 30" \
  -o "ServerAliveCountMax 3" \
  -R 2222:localhost:22 \
  user@public-server

Systemd Service for Auto-Start

[Unit]
Description=Reverse SSH Tunnel
After=network-online.target

[Service]
ExecStart=/usr/bin/autossh -M 0 -N -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -R 2222:localhost:22 user@public-server
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Security Note

Use a dedicated SSH key with restricted permissions for the tunnel. On the public server, limit what the tunnel user can do:

# In authorized_keys on public server
command="",no-agent-forwarding,no-X11-forwarding,permitopen="localhost:2222" ssh-ed25519 AAAA...

Was this article helpful?