How to Keep SSH Sessions Alive on a VPS with tmux
If you run a long job on a VPS inside tmux, the job keeps going when your SSH connection drops. tmux is a terminal multiplexer, and one of its main uses is protecting running programs on a remote server from connection drops. A tmux session survives an accidental disconnection, such as an ssh connection timeout. It also survives a detach that you choose to do.
How tmux Keeps a Session Running
tmux has two parts: a server and clients. The server starts automatically the first time you run a tmux command. It holds your sessions, windows and the programs inside them. Your terminal connects to the server as a client. When the SSH link dies, the client goes away with it, but the server and every program it holds keep running on the VPS.
By default the server exits once no sessions remain. The exit-empty option controls this, and it is on by default. A related option, destroy-unattached, destroys a session after its last client detaches. It is off by default, which is what lets a detached session wait for you.
Clients find the server through a socket in a directory named tmux-UID, where UID is your user ID. tmux creates this directory. It must not be readable, writable or executable by other users, so don't loosen its permissions to share a session.
Check tmux on Your VPS
tmux comes preinstalled on Ubuntu Server, so on a fresh Ubuntu VPS you can start a session right away. The packaged version depends on the release. Ubuntu 24.04 ships tmux 3.4 (package 3.4-1ubuntu0.2). Ubuntu 20.04 ships tmux 3.0a (package 3.0a-2ubuntu0.4).
Every command below exists in Ubuntu 20.04's tmux 3.0a, including new-session -A and attach-session -x.
Upstream supports only the latest tmux release, and new releases come out about every six months. A distribution package that is older than the current upstream release gets no upstream support. Report problems with it to your distribution first.
The Session Workflow
These are the core commands, in the order you use them:
1$ tmux new-session -s myproject
2$ tmux list-sessions
3$ tmux ls
4$ tmux attach-session -t myproject
5$ tmux a -t myproject
6$ tmux attach-session -t myproject -d
7$ tmux attach
8$ tmux kill-session -t myproject
new-session -s myproject starts a session named myproject. Every later command finds a session by its name with -t. When you reconnect a day later, a name like db-import is easier to recognise than a number.
To detach, press the prefix key and then d. The default prefix is Ctrl+b, so the full sequence is Ctrl+b, release, then d. After you detach, you can close the terminal or disconnect SSH and the session keeps running. tmux confirms the detach with a line that shows the session name, such as [detached (from session mysession)].
list-sessions, or its alias ls, shows the sessions you can attach to. attach-session -t myproject and the short form a -t myproject reconnect you to a named session. The -d variant also detaches every other client from that session.
tmux attach with no -t makes tmux choose for you. It picks the most recently used session and prefers one that no other terminal is attached to. With one session on the box that is fine. With several, pass -t so you land in the right one.
kill-session -t myproject ends the session and the programs running inside it.
Attach or Create in One Command
Typing ls and then attach after every reconnect gets old. The new-session command has a -A flag that attaches to the session if it exists and creates it if it does not:
1$ tmux new -Asmysession
The flags are packed together here: -A, then -s with the session name mysession. On a server where mysession is already running, this command behaves like attach-session. On a fresh boot, it creates the session. You can run the same line every time you log in, from your shell history or an alias, and always end up in the same place.
For scripts, has-session gives a clean test. It exits with 1 when the named session does not exist and 0 when it does. A deploy or backup script can use that exit code to check that a session exists before it sends work to it.
Reattaching From Another Machine
Say you start a job from a laptop, the connection drops, and you reconnect from a different machine. By default, attaching to a session does not detach any other client attached to it. If the laptop's client is still connected, both terminals share the session.
To take the session over, add -d, as in tmux attach-session -t myproject -d from the workflow above. This detaches every other client connected to that session.
The -x flag goes further. As well as detaching each other client, it sends SIGHUP to that client's parent process, which typically makes it exit. Use it when the old login should end as well.
The -r flag attaches read-only. A read-only client sees all the terminal output but cannot type commands or interfere with the session. That works well for letting a colleague watch a migration. Do not use read-only to let an untrusted user in, though. Access for an untrusted user is a risk even read-only.
Settings in ~/.tmux.conf
The setting most worth changing on a server is scrollback. tmux keeps 2000 lines of history per window by default. A long build or import pushes the start of its output out of that buffer. Add this line to ~/.tmux.conf to raise the limit to 10000:
1set-option -g history-limit 10000
Then reload the file into the running server from a shell:
1$ tmux source-file ~/.tmux.conf
tmux reads .tmux.conf only when the server starts, not when you create a new session. If a server is already running, editing the file does nothing until you reload it with source-file. Reloading keeps all your existing sessions, windows and panes, so it is safe to run in the middle of a job.
history-limit also applies only to new windows. Existing windows keep the limit they had when they were created. After a reload, a window that is already running a job still has 2000 lines. Open a new window for the next job to get the larger buffer.
What tmux Does Not Protect
Typing exit in the last window of a session ends the whole tmux session. Closing a pane kills the shell running in it, along with anything that shell was running. Detach with Ctrl+b d instead of exiting.
A VPS restart ends every session, because sessions live in the tmux server's memory. The tmux-resurrect plugin saves sessions and restores them after a system restart. tmux-continuum builds on it and saves automatically at regular intervals, every 15 minutes by default. Both are plugins for the Tmux Plugin Manager (TPM), which Ubuntu packages in its archive:
1$ sudo apt install tmux-plugin-manager
That package installs only the manager. You add resurrect and continuum through TPM afterwards. Plugins are third-party code, so check who maintains them before you use them on a production server. Restoring the layout does not bring back a process that a reboot killed. A half-finished import has to be restarted.
If a session disappears every time you detach, check your config for destroy-unattached. When that option is on, tmux destroys the session after its last client detaches.
Logout cleanup by systemd can also kill tmux. systemd-logind's KillUserProcesses= setting decides whether a user's processes are killed when that user logs out. Upstream systemd defaults it to yes. Ubuntu changes that default. Ubuntu 24.04 ships with KillUserProcesses=no, so a stock Ubuntu 24.04 VPS does not kill tmux at logout. Check your own value before you change anything. Look for a KillUserProcesses= line in /etc/systemd/logind.conf and in any .conf file under /etc/systemd/logind.conf.d/. If no line sets it, your distribution's default applies.
With KillUserProcesses=yes, logging out breaks tmux unless tmux runs outside the session scope. The root user is excluded by default if KillExcludeUsers= is not set. If the setting is yes and you log in as a regular user, take these two steps.
First, start the multiplexer as a user scope, which puts it outside the session scope. Second, enable lingering. Without lingering, user@.service and everything under it stop when your last session logs out. With lingering on, the service starts at boot and is not terminated when you log out. In the default configuration, users can enable lingering for themselves:
1$ systemd-run --scope --user screen
2$ loginctl enable-linger
This example is documented for screen, not tmux. The tmux form, systemd-run --scope --user tmux new -Asmysession, is an adaptation of it and not a documented command. Test it once on your VPS before you rely on it: start a session that way, log out, log back in, and check that tmux ls still lists it.
Detect Dead SSH Links Faster
tmux protects the session. It does not make SSH notice a dead connection any sooner. On the client, ServerAliveInterval defaults to 0, which means ssh sends no keepalive messages to the server. If you set ServerAliveInterval 15 and leave ServerAliveCountMax at its default, ssh disconnects about 45 seconds after the server stops responding. The per-user place for this setting is ~/.ssh/config.
The server has a matching setting. ClientAliveInterval in sshd_config also defaults to 0. With a value of 15 and ClientAliveCountMax at its default, sshd disconnects an unresponsive client after about 45 seconds.
Each setting ends a different side of the dead connection. ServerAliveInterval on your client is the one that stops your terminal freezing: ssh exits about 45 seconds after the link dies. ClientAliveInterval on the server makes sshd disconnect the dead client and end the session on the server. You can then reconnect and run tmux new -Asmysession to get back to your work.
Mosh and Byobu
Mosh is an alternative to plain SSH for connections that roam or drop often, such as laptops on mobile networks. It works alongside tmux. Mosh handles network resilience, and tmux provides session persistence and workspace management.
Byobu was installed by default on Ubuntu Server up to 25.04 Plucky. On newer releases you have to install it yourself.
Troubleshooting Attach Errors
Attach finds no session. Either there is nothing to attach to or the name is wrong. Run tmux ls to see which sessions exist and how they are spelled. If ls shows nothing, the server has exited, by default because no sessions were left. Check whether the last shell exited, the VPS rebooted, or logind killed your processes at logout.
Attach from inside tmux. Run from a shell that is already inside tmux, attach-session does not open a second copy. It switches the session you are attached to over to the target session.
Socket deleted. If something removes the tmux socket while the server is still running, send the SIGUSR1 signal to the tmux server process. The server recreates the socket, and clients can reach it again.
References
- tmux Getting Started wiki - protection from connection drops, server start and exit,
.tmux.confload timing,new -A, detach message, attach behaviour,ls, release support - tmux(1), OpenBSD manual - session persistence,
exit-empty,destroy-unattached,tmux-UIDdirectory,-A,has-sessionexit codes, SIGUSR1 socket recreation,attach-sessionwithout-t,-d,-xand-r, attach from inside tmux, read-only access for untrusted users - Terminal multiplexers, Ubuntu Server documentation - preinstalled tmux, session workflow script, prefix and detach keys, history-limit, config reload, read-only attach, closing panes and windows, TPM, resurrect, continuum, plugin caution, Mosh, Byobu
- tmux(1), Ubuntu 24.04 manual - tmux 3.4 package, history-limit applies to new windows only
- tmux(1), Ubuntu 20.04 manual - tmux 3.0a package, session commands and
-A/-xflags in 3.0a - logind.conf(5) - upstream
KillUserProcesses=default and tmux breakage, root exclusion - logind.conf(5), Ubuntu 24.04 manual - Ubuntu's
KillUserProcesses=default ofno, config file paths - systemd-run(1) - user scope example, lingering,
loginctl enable-linger - ssh_config(5), OpenBSD manual -
ServerAliveIntervaldefault and 45-second example,~/.ssh/config - sshd_config(5), OpenBSD manual -
ClientAliveIntervaldefault and 45-second example
Posts in this series
- Linux VPS Performance Tuning: sysctl & swap 2027
- Systemd Service Hardening: Sandbox a Unit (2026)
- Fail2ban on Ubuntu VPS: Stop SSH Brute Force 2026
- UFW Firewall Rules for a Public VPS: 2026 Setup
- How to Harden SSH on an Ubuntu VPS (2026 Guide)
- Automated Backups with Rsync and Cron on Linux 2026
- TLS Certificates with Certbot on an Ubuntu VPS 2026
- Harden Nginx on Ubuntu: Headers, TLS & Limits 2026
- Automatic Security Updates on Ubuntu: 2026 Setup
- Logrotate for Nginx and App Logs on a Linux VPS
- Systemd Timers: Replace Cron Jobs on a Linux VPS
- Manage Linux Users and sudo Permissions on a VPS
- Linux VPS Disk and Inode Cleanup: du, find, lsof
- journald Logs: Retention, Size Limits and Queries
- How to Install Docker on a Linux VPS
- How to Monitor a Linux VPS with Netdata
- Valkey vs Redis: Choosing a Cache for Your Linux VPS
- SQL Workbench/J: Free Multi-Database Client for a Linux VPS
- How to Install MariaDB on an Ubuntu Linux VPS
- How to Set Up WireGuard on a Linux VPS
- How to Add a Swap File on a Linux VPS
- How to Install Portainer and Manage Docker on a Linux VPS
- journald Disk Usage: Why a Short Log Line Costs Tens of KB
- Harden a systemd Service: ProtectSystem and NoNewPrivileges
- Encrypted Linux VPS Backups with restic and a systemd Timer
- Install PostgreSQL on an Ubuntu VPS With Safe Remote Access
- Keep Server Time Accurate with chrony on an Ubuntu VPS
- How to Keep SSH Sessions Alive on a VPS with tmux