Keep an SSH tunnel running: autossh, ServerAliveInterval and systemd
A tunnel stays up when ssh exits as soon as the link dies and something restarts it. Use ServerAliveInterval, ExitOnForwardFailure, and autossh or systemd.
An SSH tunnel is an ordinary ssh process. When the network drops, it either exits or, worse, hangs on a connection that no longer works. Nothing brings it back on its own. A tunnel that keeps running needs two things:
sshmust notice a dead connection and exit, instead of waiting forever.- Something must start it again after it exits.
Make ssh exit when the tunnel is broken
Put the tunnel in ~/.ssh/config on the machine that starts it:
Host tunnel-db
HostName host.example.com
User user1
LocalForward 5432 localhost:5432
ServerAliveInterval 30
ServerAliveCountMax 3
ExitOnForwardFailure yes
BatchMode yes
What each line does:
- ServerAliveInterval 30 and ServerAliveCountMax 3: if nothing arrives from the server for 30 seconds,
sshsends a check through the encrypted channel. After 3 unanswered checks it disconnects, so a dead link ends the process after about 90 seconds. The interval defaults to 0, which turns the checks off. See SSH keep-alives and idle timeouts. - ExitOnForwardFailure yes: if a forward cannot be set up, for example because its port is taken,
sshexits instead of staying connected without it. See SSH "remote port forwarding failed for listen port". - BatchMode yes: no password or host-key prompts. An unattended tunnel cannot answer them, so it needs key login with a key that does not ask for a passphrase, or an agent that already holds the key. Connect once by hand first, so the host key is saved.
Start it without a remote shell:
ssh -N tunnel-db
-N runs no remote command, which is what you want for a tunnel that only forwards ports. When something goes wrong, ssh exits with status 255.
Restart it with autossh
autossh starts ssh for you and starts it again when it dies:
autossh -M 0 -N tunnel-db
-M 0 turns off autossh's own monitoring connection. autossh then restarts ssh only when ssh exits, and the server alive checks above make sure it exits when the link is dead. The autossh manual suggests this combination with a recent OpenSSH. Without -M 0, autossh sends test data around a pair of extra forwarded ports (the given port and the next one), and nothing else may use those ports.
Behaviour worth knowing:
- If
sshfails with exit status 1 on the very first try, or fails within the first 30 seconds, autossh assumes the setup is wrong and gives up rather than retrying. The time is set with theAUTOSSH_GATETIMEenvironment variable.AUTOSSH_GATETIME=0turns this off, so autossh keeps retrying even when the first attempt fails. - After repeated quick failures, autossh waits longer and longer between attempts, up to its poll time (10 minutes by default). Send it
SIGHUPto make it retry now. autossh -fruns it in the background. Thensshcannot ask for passwords or passphrases, and the starting-gate time is 0.- To stop it, send
SIGTERMto the autossh process (for examplepkill -x autossh). autossh then ends itssshtoo. Killing only thesshprocess just makes autossh start a new one. - If
sshexits normally, for example because someone typedexitin an interactive session, autossh exits too.
Or let systemd restart it
On a Linux machine with systemd you do not need autossh. A service unit restarts plain ssh when it exits. Save this as /etc/systemd/system/tunnel-db.service:
[Unit]
Description=SSH tunnel to host.example.com
After=network-online.target
Wants=network-online.target
[Service]
User=user1
ExecStart=/usr/bin/ssh -N tunnel-db
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
Then run sudo systemctl daemon-reload and sudo systemctl enable --now tunnel-db.
- Restart=on-failure restarts the service when the process exits with an error, which includes the 255 that
sshreturns. The systemd manual recommendson-failurefor long-running services. - RestartSec=10 waits 10 seconds between attempts. The default is 100 ms, which can hit systemd's start rate limit (
StartLimitIntervalSecandStartLimitBurst) during a long outage, after which systemd stops trying. - After= and Wants=network-online.target delay the first start until the network is up.
- User=user1 runs
sshas that user, so it reads~user1/.ssh/configand that user's key.
Check it with systemctl status tunnel-db and journalctl -u tunnel-db.
When the remote end keeps the old port
A reverse tunnel (RemoteForward or ssh -R) that reconnects quickly can be refused because the server still holds the port for the dead session. The server frees it when it notices the old session is gone. Setting ClientAliveInterval on the server shortens that wait. See SSH "remote port forwarding failed for listen port".
Related
- SSH "remote port forwarding failed for listen port": why ssh -R is refused
- Port forwarding: local, remote, dynamic
- SSH keep-alives and idle timeouts
- SSH "client_loop: send disconnect: Broken pipe"
- Keep your work after a disconnect with tmux, and attach automatically
- ssh -R with port 0: let the server pick the port, and find out which one
- ssh exits with status 255: an SSH error, not your remote command
Sources
- ssh(1), options -N and EXIT STATUS
- ssh_config(5), ServerAliveInterval, ServerAliveCountMax, ExitOnForwardFailure, BatchMode
- sshd_config(5), ClientAliveInterval
- autossh(1), Debian manual page
- systemd.service(5), Restart= and RestartSec=
- systemd.unit(5), StartLimitIntervalSec= and StartLimitBurst=
- systemd.special(7), network-online.target