How to Host a Telegram Bot on a VPS: Deployment, Security and Scaling Guide

Image


Launching a Telegram bot takes only a few minutes. Keeping it reliable through updates, growing traffic and new integrations is much harder.

Most failures appear only after the bot becomes part of real business processes. Reboots, expired Webhooks, broken dependencies or configuration mistakes can leave it offline until someone notices.

In many cases, the problem is not the application but the infrastructure. Server configuration, security, automatic startup, backups and deployment are usually more important than the bot code itself.

Hosting a Telegram bot on a VPS involves much more than copying files to a server. The Linux environment must be prepared, secure access configured, Webhooks and automatic startup enabled, credentials protected and backups organised.

This guide explains how to deploy a Telegram bot on a Linux VPS so it continues running reliably after reboots, updates and increasing workloads.

When a Home Computer Stops Being the Right Place for a Telegram Bot

Most Telegram bots move to a VPS only after a series of small failures. The bot does not restart after a reboot, overnight notifications never arrive, a power outage leaves it offline until morning or an internet outage goes unnoticed for hours. Individually these incidents seem minor, but together they show that the limitation is no longer the bot itself.

The turning point comes when business processes depend on Telegram. During development, occasional downtime is rarely important. Once the bot handles customer enquiries, orders, internal notifications or business automation, every interruption has real consequences.

Support engineers regularly encounter the same situations. An online store misses new orders after a Windows update restarts the developer's PC. Lead notifications stop because the home router loses connectivity. Internal alerts disappear until someone notices the bot is offline.

As integrations with CRM systems, payment gateways, AI services and background jobs are added, reliability becomes more important than raw hardware. The problem is usually not CPU or memory but the unpredictability of a home computer, where updates, internet outages, power failures or accidentally closed processes can interrupt a service expected to run continuously.

A practical rule is simple: if you regularly check whether the bot is still running, it has already outgrown a home computer. A VPS provides automatic recovery, continuous availability and a far more reliable operating environment.

Long Polling vs Webhook: Which One Should You Use for a Production Telegram Bot?

Telegram bots receive updates using either Long Polling or Webhook. Both methods are reliable but intended for different stages of a project.

Long Polling is ideal for development. The application periodically requests updates from Telegram, allowing it to run on a local computer without a domain name, HTTPS, Nginx or a public IP address. This makes testing commands, database operations and integrations quick and straightforward.

For production, Webhook is usually the better choice. Telegram delivers updates directly to your server, reducing unnecessary requests, lowering latency and handling growing workloads more efficiently.

Webhook requires a publicly accessible server with a domain name, HTTPS and reliable network connectivity. Most production issues are caused by infrastructure rather than the bot itself, including expired SSL certificates, DNS problems or incorrect server configuration.

The practical recommendation is simple: use Long Polling during development and Webhook on a VPS for production bots that handle customer enquiries, orders, CRM integrations, payment processing or other business tasks.

This approach combines simple local development with a production environment that supports HTTPS, automatic recovery, monitoring and backups, allowing the bot to continue operating reliably after reboots, updates and traffic spikes.

Choosing the Right VPS for a Telegram Bot

Choosing a VPS for a Telegram bot is not just a matter of CPU cores and RAM. Two bots with the same number of users can generate completely different workloads depending on databases, integrations, AI services and background processing.

For bots handling notifications, enquiries or Webhook requests with a small database, 1–2 vCPUs and 1–2 GB of RAM are usually sufficient. Reliable infrastructure and fast NVMe storage are generally more important than raw processing power. At Era.Host, VPS plans starting from $5 per month are often enough for this type of deployment.

Projects using CRM systems, payment gateways, delivery services or other APIs typically benefit from 2 vCPUs and 2–4 GB of RAM, providing enough capacity for databases, background jobs and external integrations.

AI-powered bots and applications processing documents, images or videos usually require at least 2–4 vCPUs, 4 GB of RAM and fast NVMe storage, as database activity and disk performance often become more important than CPU capacity.

Support engineers frequently encounter servers with low CPU utilisation but poor performance caused by limited memory, database activity or slow storage. For Telegram bots, workload characteristics are usually far more important than user numbers.

For most projects, a VPS that can be upgraded as demand grows is a better choice than overpaying for unused resources. The goal is a balanced platform with sufficient CPU, RAM, fast NVMe storage and a straightforward upgrade path.

Preparing a Linux Server for a Telegram Bot

Many Telegram bot problems originate not from the application but from an unprepared server. Outdated packages, insecure access or incorrect system configuration often cause instability long after deployment. Spending a few minutes preparing the VPS helps avoid many operational and security issues.

Update the Operating System

Update the operating system before deploying the bot:

sudo apt update
sudo apt upgrade -y

Many server compromises exploit outdated system packages rather than vulnerabilities in the application. After updating, reboot the server and confirm that all services start correctly.

Create a Dedicated User Account

Avoid running the bot as root.

sudo adduser botuser
sudo usermod -aG sudo botuser

A dedicated account limits the impact of both security incidents and administrative mistakes.

Configure SSH Key Authentication

Replace password-based SSH access with SSH keys.

Generate a key:

ssh-keygen -t ed25519

Copy it to the server:

ssh-copy-id botuser@SERVER_IP

After confirming access, disable password authentication to prevent most automated brute-force attacks.

Configure a Firewall

Most Telegram bots require only SSH, HTTP and HTTPS.

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

Keep databases, Redis and other internal services accessible only from the local server. Once these basic steps are complete, the VPS is ready for deploying the Telegram bot.

Deploying a Telegram Bot on a VPS

Once the server is ready, deploy the application. Problems that never appeared during local development often surface here because the VPS environment differs from the developer's machine.

Uploading the Code

For most projects, Git is the simplest deployment method.

mkdir -p /opt/mybot
cd /opt/mybot
git clone https://github.com/user/mybot.git .

Private repositories require SSH keys or access tokens. Git also simplifies updates, rollbacks and version management compared with FTP or manually copying files.

Creating a Virtual Environment

Avoid installing Python packages system-wide.

cd /opt/mybot
python3 -m venv venv
source venv/bin/activate

A virtual environment isolates project dependencies and prevents conflicts with other applications.

Installing Dependencies

Install the required packages:

pip install -r requirements.txt

Verify the installation:

pip list

Missing entries in requirements.txt are a common cause of deployment failures.

Performing the First Test

Before configuring systemd, Docker or Webhooks, verify that the application starts correctly.

python bot.py

or use the project's normal startup command.

If the application uses a .env file, confirm that variables such as BOT_TOKEN, DB_HOST, DB_NAME, DB_USER and DB_PASSWORD are present.

After startup, test message handling, database connectivity, external APIs and logging. Once the application works correctly, continue with automatic startup using systemd.

Why systemd Is the Standard for Linux Services

Running a Telegram bot with systemd turns it into a standard Linux service. The application starts automatically after a reboot, restarts after failures, runs in the background, writes logs to the system journal and can be managed with standard Linux commands. This is more reliable than using screen, tmux or an SSH session.

Creating a systemd Service

Assuming the application is installed in:

/opt/mybot

and the virtual environment is located in:

/opt/mybot/venv

create a service file:

sudo nano /etc/systemd/system/mybot.service

Example configuration:

[Unit]
Description=Telegram Bot
After=network.target

[Service]
Type=simple
User=botuser
WorkingDirectory=/opt/mybot
ExecStart=/opt/mybot/venv/bin/python /opt/mybot/bot.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target

Here, User specifies the account running the bot, WorkingDirectory defines the project location and ExecStart launches the application. Restart=always automatically restarts the service after failures.

Enabling the Service

sudo systemctl daemon-reload
sudo systemctl enable mybot
sudo systemctl start mybot
sudo systemctl status mybot

If configured correctly, the service should report active (running).

Viewing Logs

View recent logs:

journalctl -u mybot

Monitor them in real time:

journalctl -u mybot -f

These logs are usually the fastest way to identify startup failures, missing dependencies, configuration errors and database connection problems.

Configuring Webhooks for a Telegram Bot

Most Telegram bots use Long Polling during development and Webhooks in production, where they provide lower latency, fewer unnecessary requests and a more reliable architecture.

Preparing a Domain

A Webhook requires a publicly accessible domain, for example:

bot.example.com

Verify that it resolves to the VPS:

ping bot.example.com

or

dig bot.example.com

Installing and Configuring Nginx

Install Nginx:

sudo apt install nginx -y
sudo systemctl status nginx

Create a virtual host:

sudo nano /etc/nginx/sites-available/bot

Example configuration:

server {
    listen 80;
    server_name bot.example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Enable the configuration:

sudo ln -s /etc/nginx/sites-available/bot /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Installing HTTPS

Telegram Webhooks require HTTPS.

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d bot.example.com
sudo certbot renew --dry-run

Registering the Webhook

Register the endpoint:

curl -F "url=https://bot.example.com/webhook" \
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook

Verify the configuration:

curl https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo

If the correct URL is returned without delivery errors, the Webhook is configured successfully.

Common Problems

Most Webhook failures are caused by infrastructure rather than Telegram itself. Common causes include incorrect DNS records, blocked port 443, Nginx configuration errors, expired SSL certificates, incomplete DNS propagation or a Webhook that still points to the previous VPS after migration.

Once DNS, Nginx, HTTPS and the Webhook are configured correctly, Telegram delivers updates directly to the application, providing faster and more reliable message processing than Long Polling.

Securing Your Telegram Bot Token

A Telegram bot token should never be stored in the source code. Hardcoding it may be convenient during development, but it becomes a security risk once the project is shared, deployed or committed to Git.

Store sensitive values in a .env file.

Example:

BOT_TOKEN=123456789:AAExampleTokenValue
DB_HOST=localhost
DB_NAME=mybot
DB_USER=mybot_user
DB_PASSWORD=strong_password

For Python, install python-dotenv:

pip install python-dotenv

Load the configuration:

import os
from dotenv import load_dotenv

load_dotenv()

BOT_TOKEN = os.getenv("BOT_TOKEN")

if not BOT_TOKEN:
    raise RuntimeError("BOT_TOKEN is not set")

This allows the same codebase to use different settings in development, staging and production.

Restrict access to the configuration file:

sudo chown botuser:botuser /opt/mybot/.env
sudo chmod 600 /opt/mybot/.env

Only the application owner should be able to read the file.

Exclude .env from Git:

.env
*.env
.env.local

If a token has ever been exposed, generate a new one with BotFather, update the server configuration and verify that the application is using the replacement credentials.

A secure deployment keeps source code in Git, stores secrets in .env, restricts file permissions and runs the bot under a dedicated service account using systemd or Docker.

Setting Up Backups for a Telegram Bot

Many Telegram bot owners only think about backups after the first serious failure. While the code is stored in Git, the database, user records, logs, uploaded files and configuration often exist in only one place. Rebuilding the application is easy compared with recovering lost data.

A complete backup should include the database, application files, the .env file, web server configuration and systemd service definitions.

For PostgreSQL:

pg_dump -U mybot_user mybot_db > /backup/mybot_$(date +%F).sql

For MySQL:

mysqldump -u mybot_user -p mybot_db > /backup/mybot_$(date +%F).sql

Back up the application files:

tar -czf /backup/mybot_files_$(date +%F).tar.gz /opt/mybot

Never keep backups only on the production VPS. Store them on a second server, object storage, a cloud backup service or another independent location.

Automate backups with cron.

Open the cron configuration:

crontab -e

Run the backup every day at 03:00:

0 3 * * * /opt/scripts/backup.sh

Backups should also be tested regularly on a separate server to confirm that archives are intact, database dumps contain valid data and the recovery process works as expected.

For production Telegram bots, backups are part of the infrastructure rather than an optional precaution. A recent, tested backup can reduce recovery from hours to just a few minutes.

Monitoring a Telegram Bot

A common mistake after deploying a Telegram bot is assuming that if it worked yesterday, it is still working today. Manual checks may be acceptable during development, but production bots require continuous monitoring.

Monitoring Availability with Uptime Kuma

Uptime Kuma is a practical monitoring solution for Webhook endpoints and related services.

For a Webhook-based bot, configure an HTTP monitor with:

Monitor type: HTTP(s)

URL: https://bot.example.com/webhook

Check interval: 60 seconds

Expected status: 200 OK

This allows failures to be detected before users notice them.

Monitoring Logs

Availability checks only confirm that the service responds. Database errors, failed API requests and integration problems usually appear in the logs first.

View recent logs:

journalctl -u mybot

Monitor them in real time:

journalctl -u mybot -f

Telegram Alerts

Configure Telegram notifications in Uptime Kuma by creating a BotFather bot, obtaining its token, specifying the destination Chat ID and assigning the notification channel to the required monitors.

Example alert:

Monitor: Telegram Bot Webhook
Status: DOWN
Time: 02:17
Reason: HTTP 500 Internal Server Error

What Should Be Monitored?

Monitor the Webhook, bot process, available disk space, memory usage, database availability, backup execution, SSL certificate validity, VPS uptime and connectivity to external APIs. Many production failures are caused by supporting services rather than the bot itself.

For production Telegram bots, monitoring is as important as backups and security. Detecting problems within minutes helps prevent service interruptions and reduces recovery time.

Image
Previous Post Next Post