autossh as a Systemd Service
Make the tunnel start at boot, run in the background, and come back by itself, using a small systemd unit.
What I learned#
autossh keeps a tunnel alive, but only while a terminal is open. To make it survive closed terminals and reboots, let systemd own the process.
Create a unit file at /etc/systemd/system/autossh-tunnel.service:
[Unit]
Description=Persistent reverse SSH tunnel
After=network-online.target
Wants=network-online.target
[Service]
User=tunnel
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -N \
-i /home/tunnel/.ssh/id_ed25519 \
-o "ServerAliveInterval 30" \
-o "ServerAliveCountMax 3" \
-o "ExitOnForwardFailure yes" \
-R 8080:localhost:22 user@example.com
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Then load it and start it now and at every boot:
sudo systemctl daemon-reload
sudo systemctl enable --now autossh-tunnel
Check that it works:
systemctl status autossh-tunnel
journalctl -u autossh-tunnel -f
A few details that matter:
- Do not use
-f. That option sends autossh to the background by itself, but systemd expects the process to stay in the foreground and handles the background part. - Use the full path in
ExecStart. Find it withcommand -v autossh. - Run it as a normal user, not root. A dedicated
tunneluser with a key that is only used for this is even better. - The first connection to a host asks you to confirm its fingerprint. A service cannot answer that question, so log in once as the same user and accept it, so it is saved in
known_hosts. After=network-online.targetwaits for the network before starting, andWants=makes sure that target is actually pulled in.
Why it matters#
There are now two layers of recovery. SSH keepalives notice a dead connection and make ssh exit, and autossh restarts it. If autossh itself ever crashes, Restart=always makes systemd start it again after 10 seconds.
This is also what turns the tunnel from something I babysit into something I forget about, which is the goal. It is the same idea as in zombie SSH: do not trust that something is alive, build something that recovers when it is not.