Linux β€’ Infrastructure & Tunnels

How to Keep Reverse SSH Tunnel Persistent with Autossh & Systemd

A reverse SSH tunnel forwards a local port on an inaccessible private network to a public cloud VPS. Wrapping `autossh` in a systemd service monitors connection drops and reconnects automatically within seconds.

/etc/systemd/system/reverse-tunnel.service
[Unit]
Description=Auto-Healing Reverse SSH Tunnel
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=ubuntu
ExecStart=/usr/bin/autossh -M 0 -N -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -o "ExitOnForwardFailure yes" -R 2222:localhost:22 remote-user@my-vps.com -i /home/ubuntu/.ssh/id_rsa
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
Customize:
User:
WorkingDir:
ExecStart:

Systemctl Lifecycle & Journalctl Monitoring

sudo systemctl daemon-reloadLoad unit file
sudo systemctl enable --now reverse-tunnelEstablish persistent tunnel
sudo journalctl -u reverse-tunnel -fCheck connection logs

Linux & Systemd Production Best Practices

  • Use `Wants=network-online.target` and `After=network-online.target` so autossh does not attempt to connect before WiFi or Ethernet has obtained an IP address.
  • Always test passwordless SSH key authentication manually before starting the systemd service.

Frequently Asked Questions About Persistent Reverse SSH Tunnel

Frequently Asked Questions

Frequently Asked Questions

Everything you need to know regarding specifications, syntax, and security best practices.

`-M 0` disables autossh's legacy monitoring port and relies on OpenSSH's built-in `ServerAliveInterval` probes instead.