Discord Bot Hosting with PM2: Zero-Downtime Process Management
Your Discord bot will crash occasionally. That is not a prediction — it is a certainty. A database connection will drop, an unhandled edge case in your code will throw an exception, Discord's API will time out. What matters is how quickly your bot recovers. PM2 makes recovery automatic and configurable.
PM2 Ecosystem Configuration
Instead of simple pm2 start commands, use an ecosystem file for production configuration:
// ecosystem.config.js
module.exports = {
apps: [{
name: 'discord-bot',
script: 'src/index.js',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '256M', // Auto-restart if memory exceeds 256 MB
restart_delay: 5000, // 5s delay between restart attempts
max_restarts: 10, // Stop restart loop after 10 crashes in time window
min_uptime: '30s', // Must run 30s to be considered "started"
env: {
NODE_ENV: 'production',
DISCORD_TOKEN: process.env.DISCORD_TOKEN
},
log_date_format: 'YYYY-MM-DD HH:mm:ss',
error_file: '/var/log/bot/error.log',
out_file: '/var/log/bot/out.log',
combine_logs: false
}]
};
Start with:
pm2 start ecosystem.config.js
pm2 save
The max_restarts Setting
This is critical for preventing crash loops. If your bot crashes repeatedly in a short window (Discord token revoked, database down), PM2 should stop trying to restart and alert you rather than spam restart attempts.
max_restarts: 10, // Max restarts in restart_delay * max_restarts window
min_uptime: '30s', // If bot hasn't run for 30s, it's a crash (not a clean shutdown)
If the bot crashes more than 10 times without achieving 30 seconds of uptime, PM2 marks it as "errored" and stops trying. You are then alerted (see monitoring below) rather than spinning in infinite crashes.
Zero-Downtime Deployment
For bots that handle active user interactions, reloading commands during a deployment is gracefully handled by pm2 reload:
git pull && pm2 reload discord-bot
pm2 reload sends SIGINT first (graceful shutdown), waits for the process to exit cleanly, then starts a new instance. This minimises the gap versus pm2 restart (which sends immediate kill and restarts).
Monitoring PM2 Status
pm2 status # Current state of all processes
pm2 logs bot-name # Live log tail
pm2 monit # Interactive dashboard in terminal
For alerting when the bot crashes, integrate PM2 with webhooks:
pm2 install pm2-discord
pm2 set pm2-discord:discord_url https://discord.com/api/webhooks/YOUR_WEBHOOK_URL
PM2 will post a Discord notification when any managed process crashes.