Running the bot in the background¶
In this article
To have a Python (or any other) bot run continuously, automatically restart on failures, and start after server reboot, simply running python main.py is not enough. You need a full‑fledged background service.
Below are three proven methods: from the simple screen to the industrial‑grade systemd. Choose based on your requirements.
Preparing the environment¶
-
Place the bot code, e.g., in
/home/user/bot: -
Create and activate a virtual environment to isolate dependencies:
-
Install dependencies:
-
Test manual launch:
Note
Do not run the bot as root unless necessary. It's better to create a dedicated user:
# Ubuntu / Debian
sudo adduser --disabled-login botuser
# CentOS / AlmaLinux / Rocky Linux
sudo useradd -m -s /sbin/nologin botuser
sudo chown -R botuser:botuser /home/user/bot
Make sure that botuser has read access to the /home/user directory (otherwise the service will not be able to open /home/user/bot).
Method 1. screen - quick launch (for testing and development)¶
Pros: easiest to get started.
Cons: does not restart after a crash or reboot — not suitable for production.
Installation:
# Ubuntu / Debian
sudo apt update && sudo apt install screen -y
# CentOS 7
sudo yum install -y screen
# AlmaLinux / Rocky Linux 9–10 (the package is in EPEL)
sudo dnf install -y epel-release && sudo dnf install -y screen
Note
Instead of screen, you can use tmux — it is available in the standard repositories of all the distributions listed above.
Launch:
Management:
| Action | Command |
|---|---|
| Detach from session (leave in background) | Ctrl + A, then D |
| View list of sessions | screen -ls |
| Return to session | screen -r bot |
| Terminate session from inside | Ctrl + A, then K > Y |
Information
Upon server reboot or script crash, the bot will remain stopped. Use only for temporary tasks.
Method 2. systemd - Linux standard for services (recommended)¶
Pros: autostart, restart on errors, logging, system integration.
Cons: requires writing a config.
-
Create a unit file:
-
Paste the config (adapt paths and user!):
[Unit] Description=Telegram Bot Service After=network.target StartLimitIntervalSec=30 StartLimitBurst=5 [Service] Type=simple # It is recommended not to run as root User=botuser Group=botuser WorkingDirectory=/home/user/bot ExecStart=/home/user/bot/venv/bin/python /home/user/bot/main.py Restart=always RestartSec=10 # So that logs are not buffered Environment="PYTHONUNBUFFERED=1" # Security (optional, but recommended) NoNewPrivileges=true PrivateTmp=true ProtectSystem=strict # The bot code is located in /home, so the directory is mounted read-only ProtectHome=read-only # Directory the bot is allowed to write to (if needed; "-" means it is not an error if it does not exist) ReadWritePaths=-/home/user/bot/data [Install] WantedBy=multi-user.target
Attention
In systemd unit files, comments are only allowed on a separate line starting with # or ;. A comment at the end of a line with a parameter becomes part of its value, and the service will fail to start.
-
Enable the service:
-
Check status and logs:
Security tips
Restrict the service from accessing unnecessary parts of the system (via ProtectSystem, ProtectHome, ReadOnlyPaths);
Limit the network capabilities of the service: RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX allows only IPv4/IPv6 network sockets and local sockets, while IPAddressDeny=/IPAddressAllow= let you define a list of allowed addresses;
You can additionally use ProtectKernelTunables=true, ProtectControlGroups=true, PrivateDevices=true;
Use RuntimeDirectory= for temporary files;
You can assess the isolation level of the service with systemd-analyze security bot.service.
Method 3. PM2 - process manager (for Node.js, but supports Python)¶
Pros: simplicity, built‑in logs, monitoring, web interface.
Cons: requires Node.js, overkill for simple Python bots.
Installation:
# Install Node.js and npm (if not already installed)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
# Install PM2 globally
sudo npm install -g pm2
Start the Python bot:
Useful commands:
| Command | Purpose |
|---|---|
pm2 list | List of processes |
pm2 logs my-bot | View logs |
pm2 monit | Real‑time monitoring |
pm2 startup | Configure autostart after reboot |
pm2 save | Save current processes |
Information
After pm2 startup, follow the terminal instructions — PM2 will generate a systemd unit for autostart.
Method Comparison¶
| Criterion | screen | systemd | PM2 |
|---|---|---|---|
| Autostart after reboot | No | Yes | Yes (requires pm2 startup) |
| Restart on crash | No | Yes | Yes |
| Logging | Only in session | journalctl | Built‑in logs |
| Security | Low | High (isolation settings) | Medium |
| Configuration complexity | Low | Medium | Low (but requires Node.js) |
| Suitable for production | No | Recommended | Yes (if already using Node.js) |
Additional
Set up alerting when the bot stops (e.g., via systemd + healthchecks.io);
Regularly update dependencies pip list --outdated;
Use .env files and python-dotenv to store tokens (and exclude them from Git!).