Configuring a reliable, persistent SSH tunnel prevents connections from dropping due to network changes or idle firewalls. Building a robust, “always-on” tunnel requires combining OpenSSH’s native network keep-alives with a service manager to auto-restart the connection if it fails. Core Keep-Alive Parameters
Standard SSH tunnels die silently when routers or firewalls drop idle TCP sessions. To solve this, inject keep-alive packets into the encrypted stream using these client-side variables:
ServerAliveInterval 30: Sends an encrypted heartbeat probe to the server after 30 seconds of absolute idleness.
ServerAliveCountMax 3: Dictates how many consecutive heartbeats can go unanswered before the client forces a hard disconnect.
ExitOnForwardFailure yes: Forces the primary SSH process to close entirely if the requested port forwarding fails to bind. This is crucial for triggering automated script or service restarts. Option 1: The Production Standard (systemd)
Deploying a native systemd service is the cleanest, most robust way to manage persistent tunnels on modern Linux systems without relying on third-party tools.
Generate SSH Keys: Set up passwordless authentication using ssh-keygen and ssh-copy-id.
Create Service File: Open a blank unit file at /etc/systemd/system/ssh-tunnel.service:
[Unit] Description=Persistent SSH Tunnel After=network.target [Service] Type=simple User=your_local_user ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -L 8080:localhost:80 user@remote_server Restart=always RestartSec=15 [Install] WantedBy=multi-user.target Use code with caution. Command breakdown:
-N: Do not execute remote commands (ideal for port forwarding only). -T: Disable pseudo-terminal allocation.
Restart=always: Tells systemd to instantly spin the process back up if it dies.
RestartSec=15: Waits 15 seconds before retrying to prevent aggressive log throttling during network outages.
Activate Tunnel: Reload the daemon, enable it at boot, and start it.
sudo systemctl daemon-reload sudo systemctl enable ssh-tunnel.service sudo systemctl start ssh-tunnel.service Use code with caution. Option 2: The Legacy Automator (autossh)
If you work on platforms lacking systemd, autossh is a purpose-built utility designed exclusively to monitor and restart broken SSH connections.
Install it via your local package manager (sudo apt install autossh or brew install autossh), then execute it:
autossh -M 0 -NT -o “ServerAliveInterval 30” -o “ServerAliveCountMax 3” -o “ExitOnForwardFailure yes” -L 8080:localhost:80 user@remote_server Use code with caution.
-M 0: Disables autossh’s legacy built-in echo port monitoring. This hands monitoring duties off entirely to the much more reliable native OpenSSH ServerAlive loop. Server-Side Safeguards How to reliably keep an SSH tunnel open? – Super User
Leave a Reply