Deploy a Node.js Telegram bot with PM2

PM2 is the Node.js process manager you actually want: ecosystem files for declarative config, automatic log rotation, restart on crash, and integration with systemd so it survives reboots. Twenty-minute setup from ssh to a bot that runs unattended.

Disclosure: contains an affiliate link to Inferno VPS.

Why PM2 instead of systemd directly

Both work. The trade-off:

For a Node.js bot, PM2 wins on developer ergonomics. For a polyglot host running bots in multiple languages, systemd's uniformity is nicer.

Prerequisites

Tested on Ubuntu 22.04, Node.js 20 LTS, PM2 5.4, grammy 1.30, on a $3.49 Inferno VPS.

Step 1 — Install Node.js LTS

Use the NodeSource repository, not Ubuntu's old nodejs package:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
node --version    # v20.x.x
npm --version

Step 2 — Create the bot user and install PM2

sudo adduser --disabled-password --gecos "" botuser
sudo mkdir -p /home/botuser/.ssh
sudo cp ~/.ssh/authorized_keys /home/botuser/.ssh/
sudo chown -R botuser:botuser /home/botuser/.ssh
sudo chmod 700 /home/botuser/.ssh
sudo chmod 600 /home/botuser/.ssh/authorized_keys

# PM2 is global, but installed per-user — install as botuser
sudo -iu botuser
npm install -g pm2
pm2 --version

Step 3 — Minimal bot with grammy

We'll use grammy — the modern, TypeScript-friendly Node.js library for Telegram bots. node-telegram-bot-api also works; grammy is faster, smaller, and better maintained.

mkdir mybot && cd mybot
npm init -y
npm install grammy dotenv

Create bot.js:

import "dotenv/config";
import { Bot } from "grammy";

const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN);

bot.command("start", (ctx) => ctx.reply("Hello! I'm alive on a VPS."));
bot.on("message:text", (ctx) => ctx.reply(ctx.message.text));

bot.catch((err) => {
  console.error("Bot error:", err);
});

await bot.start({
  drop_pending_updates: true,
  onStart: (info) => console.log(`@${info.username} is up`),
});

// Graceful shutdown
process.once("SIGINT", () => bot.stop());
process.once("SIGTERM", () => bot.stop());

Edit package.json to declare ES modules:

{
  "type": "module",
  "scripts": {
    "start": "node bot.js"
  }
}

Step 4 — Environment file

cat > .env <<EOF
TELEGRAM_BOT_TOKEN=123456:ABC...
EOF
chmod 600 .env

Step 5 — Test manually first

node bot.js
# Message your bot on Telegram — should respond
# Ctrl+C to stop

Confirm the bot works under your own user before handing it to PM2.

Step 6 — Ecosystem file

Create ecosystem.config.cjs (note the .cjs — PM2 expects CommonJS):

module.exports = {
  apps: [
    {
      name: "mybot",
      script: "./bot.js",
      cwd: "/home/botuser/mybot",
      interpreter: "node",
      node_args: "--enable-source-maps",
      instances: 1,
      exec_mode: "fork",
      autorestart: true,
      watch: false,
      max_memory_restart: "200M",

      env_file: ".env",
      env: {
        NODE_ENV: "production",
        TZ: "Europe/Helsinki",
      },

      log_date_format: "YYYY-MM-DD HH:mm:ss Z",
      out_file: "/home/botuser/mybot/logs/out.log",
      error_file: "/home/botuser/mybot/logs/err.log",
      merge_logs: true,

      min_uptime: "30s",
      max_restarts: 10,
      restart_delay: 5000,
      exp_backoff_restart_delay: 5000,
    },
  ],
};

Step 7 — Install log rotation

PM2 doesn't rotate its log files by default — the second most common "the disk filled up" cause for Node hosts. Install the module:

pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
pm2 set pm2-logrotate:compress true

Step 8 — Start the bot

mkdir -p logs
pm2 start ecosystem.config.cjs
pm2 ls
pm2 logs mybot --lines 50

You should see the "@yourbot is up" line and your bot should respond on Telegram.

Step 9 — Survive reboots

This is the step everyone forgets. PM2 has a startup command that integrates with systemd:

pm2 save                                          # snapshot the process list
# Generate the systemd init command — copy/paste what it prints
pm2 startup systemd -u botuser --hp /home/botuser
# That prints a line like:
#   sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u botuser --hp /home/botuser
# Run it (with sudo, as instructed)

Reboot the VPS (sudo reboot). When it comes back, pm2 ls as botuser should show your bot running.

Daily PM2 commands

pm2 ls                       # all processes
pm2 logs mybot               # follow logs
pm2 logs mybot --lines 200   # last 200 lines
pm2 restart mybot
pm2 reload mybot             # zero-downtime restart (cluster mode only)
pm2 stop mybot
pm2 delete mybot
pm2 monit                    # CPU / RAM dashboard in terminal
pm2 describe mybot           # all settings for one process

Updating the bot

cd /home/botuser/mybot
git pull
npm install                  # if dependencies changed
pm2 restart mybot
pm2 logs mybot --lines 30

For a true zero-downtime restart you need cluster mode (exec_mode: "cluster", instances: 2) — but a Telegram bot in long-polling mode can't be clustered (only one process can hold the polling lock). Webhook bots can. See webhook vs polling.

Common PM2 mistakes

"PM2 doesn't survive reboot"

You didn't run pm2 save after the last change, or you didn't run the pm2 startup systemd integration. Re-do both.

"Logs file is 20 GB"

You forgot to install pm2-logrotate. Install it now and configure the size limits.

"Bot starts, then dies in < 30 seconds"

The min_uptime: "30s" + max_restarts: 10 combo. If the bot crashes before 30s of uptime, PM2 counts it as a failed restart; after 10 fast failures, PM2 stops trying. pm2 logs mybot will show the crash reason — usually missing env var or auth error.

"Bot uses way more RAM than expected"

The max_memory_restart: "200M" safety net triggers a restart when the bot exceeds it. Investigate why — usually unbounded caches or leaked listeners.

"Two bots run simultaneously after restart"

You have instances: 2 with exec_mode: "cluster" on a long-polling bot. Both compete for the polling lock; Telegram rejects one. Either drop to single instance or move to webhooks.

VPS for a small fleet of Node bots?

PM2's footprint plus 2-3 small bots fits in a 1 GB plan. The Inferno $3.49 plan handles this comfortably; bump to 2 GB if you also co-host other services.

View Inferno plans →

What to do next


Author: Daniel Ferro — Lisbon. Last tested: 2026-05-22 on Node.js 20 LTS, PM2 5.4, grammy 1.30.