Keeping Programs Running
A program you start in SSH stops when you close the connection. To keep a bot or app running, use screen for a quick session you can come back to, or systemd to start it at boot and restart it if it crashes.
The examples run a Python bot in /root/my-bot with python3 bot.py. Replace the folder and command with your own, for example node index.js.
screen
Section titled “screen”Install screen and start a named session:
apt install screen # Debian and Ubuntudnf install screen # Rocky Linux and AlmaLinuxscreen -S my-botStart your program inside the session:
cd /root/my-botpython3 bot.pyPress Ctrl+A, then D, to leave the session running in the background. You can close SSH.
| To | Run |
|---|---|
| List sessions | screen -ls |
| Go back to a session | screen -r my-bot |
| Stop the program | Go back to the session and press Ctrl+C |
systemd
Section titled “systemd”Create a service file:
nano /etc/systemd/system/my-bot.servicePaste this and change WorkingDirectory and ExecStart to match your program:
[Unit]Description=My Discord botAfter=network-online.targetWants=network-online.target
[Service]WorkingDirectory=/root/my-botExecStart=/usr/bin/python3 bot.pyRestart=on-failureUser=root
[Install]WantedBy=multi-user.targetSave with Ctrl+X, then Y and Enter. Start the service and enable it at boot:
systemctl daemon-reloadsystemctl enable --now my-bot| To | Run |
|---|---|
| Check if it runs | systemctl status my-bot |
| Follow its output | journalctl -u my-bot -f |
| Restart it after a code change | systemctl restart my-bot |
| Stop it | systemctl stop my-bot |
ExecStart needs the full path to the program. Find it with which python3 or which node. If your bot uses a
Python virtual environment, point ExecStart at the environment’s Python, for example
/root/my-bot/venv/bin/python bot.py.