Keep a Program Running on Linux

A program that you start in an SSH session stops when you close the session. This page shows two ways to keep it running: tmux for programs you want to watch and use by hand, and a systemd service for programs that should always run and start again after a restart. The commands were tested on Ubuntu 26.04 LTS.


tmux: a Terminal That Stays Open

tmux is already installed on Ubuntu. Start a session with a name:

tmux new -s work

A green bar at the bottom shows that you are inside tmux. Start your program as usual.

A program running inside the tmux session work

To leave the program running, press Ctrl+B, release both keys, then press D. You are back in your normal terminal, and you can close the SSH session. Later, connect again and go back to the program:

tmux ls
tmux attach -t work

tmux ls lists your sessions. To end a session, stop the program and type exit inside tmux.

tmux sessions do not survive a restart of the server. For that, use a service.

systemd: a Program That Always Runs

A service starts with the server, runs in the background and is started again if it crashes. As an example, this service runs a small web server on port 8000 as the user alex, from the folder /home/alex/myapp. Replace the user, the folder and the ExecStart line with your own program; ExecStart needs the full path to the program.

Create the file /etc/systemd/system/myapp.service as root (for example with nano /etc/systemd/system/myapp.service):

[Unit]
Description=My app
After=network-online.target
Wants=network-online.target

[Service]
User=alex
WorkingDirectory=/home/alex/myapp
ExecStart=/usr/bin/python3 -m http.server 8000
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Load the new file, then start the service and let it start with the server:

systemctl daemon-reload
systemctl enable --now myapp

Check that it runs: active (running) in the third line.

systemctl status myapp

What the program writes goes to the system log. To see it (add -f to follow new lines):

journalctl -u myapp

If the program crashes, Restart=on-failure starts it again after 5 seconds. The log then shows Scheduled restart job.

Control the Service

systemctl restart myappRestart, for example after you changed the program's settings
systemctl stop myappStop it until the next start of the server
systemctl disable --now myappStop it and do not start it with the server any more

After every change to the .service file, run systemctl daemon-reload and then systemctl restart myapp.

Reach it from outside

If the firewall is on, open the program's port: Protect Your Linux Server With a Firewall and Fail2ban.


Related Guides

View all Linux guides

Was this answer helpful? 0 Users Found This Useful (0 Votes)