Keep programs running after closing the window (screen, tmux)
When you close an SSH window, programs you started in it shut down too. screen and tmux create a "virtual window" on the server so your programs keep running even after you disconnect from SSH. You only need to learn one of the two.
For programs that must always be on and should start again automatically when the server reboots, like Discord bots or web apps, pm2 or systemd is a better fit. (Hosting a Discord bot 24/7 (discord.js, discord.py), Deploying your own web app to a server) screen and tmux are good for game servers where you type commands directly into the console, and for tasks that take a long time.
screen
sudo apt install -y screen
screen -S work # Creates a window named 'work' and takes you into it
Run whatever program you want inside this window.
| What you want to do | How |
|---|---|
| Leave while keeping the program running | Press Ctrl + A, then D |
| Go back in | screen -r work |
| List your windows | screen -ls |
| Close a window completely | exit inside the window |
| Scroll up | Press Ctrl + A, then Esc; move with the arrow keys; Esc to finish |
If screen -r says (Attached) and won't let you in, your previous SSH connection is still holding on to it. Go in with screen -d -r work.
tmux
sudo apt install -y tmux
tmux new -s work
| What you want to do | How |
|---|---|
| Leave while keeping the program running | Press Ctrl + B, then D |
| Go back in | tmux attach -t work |
| List your windows | tmux ls |
| Close a window completely | exit inside the window |
| Scroll up | Press Ctrl + B, then [; move with the arrow keys; q to finish |
Things to watch out for
- If you press
Ctrl + Cto leave, the program shuts down. Always leave withCtrl + A, D(screen) orCtrl + B, D(tmux). - When the server reboots, every program inside screen/tmux shuts down. To have them start again automatically after a reboot, use cron's @reboot or pm2/systemd.
- How to run a Minecraft server with screen is also covered in Creating a Minecraft server (Java Edition, Paper and vanilla).