Linux: How to create an SSH tunnel as a systemd service
Published in
3 min readNov 22, 2021
Much often you will need a constant SSH tunnel connection, to avoid the administrative load for those tunnels after a reboot is to configure them as systemd services and use SSH keys to avoid passwords.
Also its nice and super helpfull to create the systemd service as a template that can accept tunnel parameters from a file, this allow very easily to manage your tunnels (add,delete,modify,start,stop).
This configuration requires ssh keys in order to communicate with the SSH Gateway
Create the following template file
/etc/systemd/system/secure-tunnel@.service
Content:
[Unit]
Description=Setup a secure tunnel to %I
After=network.target[Service]
Environment="LOCAL_ADDR=localhost"
EnvironmentFile=/etc/default/secure-tunnel@%i
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -L ${LOCAL_ADDR}:${LOCAL_PORT}:${REMOTE_HOST}:${REMOTE_PORT} ${TUSER}@${TARGET}# Restart every >2 seconds to avoid StartLimitInterval failure
RestartSec=5
Restart=always[Install]
WantedBy=multi-user.target
Explanation of the file variables
- ${LOCAL_ADDR} ← The local ip to bind the tunnel