This guide explains how to create a persistent SSH reverse tunnel using systemd without relying on tools like autossh. This approach automatically restarts the SSH tunnel if it fails or gets stuck due to disconnections.
Using systemd provides several benefits over standalone SSH or autossh:
- Automatic Restart: If the SSH connection fails,
systemdrestarts it automatically. - Keep Alive: Prevents stale SSH connections by using SSH's
ServerAliveIntervalandServerAliveCountMax. - Clean and Simple: Avoids external tools and manages the service with native system management.
Ensure ssh is installed:
sudo apt install openssh-clientCreate a service file in /etc/systemd/system/ssh-tunnel.service:
sudo nano /etc/systemd/system/ssh-tunnel.service[Unit]
Description=Persistent SSH Tunnel
After=network.target
[Service]
Type=exec
ExecStart=/usr/bin/ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -Nn -R 7070:localhost:22 <remote_host> 'sleep 20m'
Restart=always
RestartSec=20
RuntimeMaxSec=30m
[Install]
WantedBy=default.target- ServerAliveInterval=60: Sends keep-alive packets every 60 seconds.
- ServerAliveCountMax=3: Terminates the connection if 3 keep-alive packets are unanswered (180 seconds total).
- ExitOnForwardFailure=yes: Ensures the service exits if port forwarding fails.
Start and enable the service so it runs at boot:
sudo systemctl start ssh-tunnel
sudo systemctl enable ssh-tunnelVerify the service is running:
sudo systemctl status ssh-tunnelThis configuration ensures a reliable reverse SSH tunnel that automatically reconnects after failure, preventing stale connections and minimizing manual intervention.