How to Run a Bot or Script on a VPS 24/7: systemd, pm2, screen
A Telegram bot, a scraper or a queue worker has to run all the time — after you close the terminal and after the server restarts. A VPS offers three ways to do this.
Permanent processes do not run on shared hosting. There, use cron for scheduled tasks, and Bot Panel or a VPS for bots.
1. systemd — the most reliable
A service starts with the server and restarts by itself if it crashes. Create the file /etc/systemd/system/mybot.service:
[Unit]
Description=My bot
After=network.target
[Service]
User=bot
WorkingDirectory=/home/bot/app
ExecStart=/usr/bin/python3 /home/bot/app/bot.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.targetEnable and start the service, then check its status and log:
systemctl daemon-reload
systemctl enable --now mybot
systemctl status mybot
journalctl -u mybot -fSet User to a separate user, not root, and use the full interpreter path in ExecStart (find it with which python3 or which node).
2. pm2 — for Node.js
npm install -g pm2
pm2 start app.js --name mybot
pm2 save
pm2 startupThe pm2 startup command prints a line — run it so the processes start after a reboot. Log: pm2 logs mybot.
3. screen or tmux — for one-off tasks
Use it for a long command that must finish after you disconnect: screen -S job, run the command, detach with Ctrl+A, then D. To return: screen -r job. Such a process does not start again after a server reboot — for permanent work use systemd or pm2.