24/7 Discord Bot Hosting on Linux: Production Deployment with PM2 Process Manager
· 5 min read
When building a Discord bot withdiscord.js(Node.js) ordiscord.py(Python), keeping it running reliably 24/7 is essential. Starting a bot in a regular SSH session terminates the process as soon as the terminal disconnects or an unhandled exception occurs.
1. What Is PM2 and Why Does It Outperform Screen/Tmux?
ThePM2process manager provides a complete production runtime for bots and microservices:
- Automatic Crash Recovery:If your bot throws an unhandled exception (e.g. a Discord API
500 Internal Server Error), PM2 restarts the process within milliseconds. - Systemd Boot Persistence:Native integration with
systemdensures your bots start automatically whenever the host machine reboots. - Real-Time Resource Telemetry:Live CPU usage, RAM threshold restarts, and log rotation.
2. Installing Node.js & PM2
# Instalacja Node.js LTS oraz PM2 globalnie
sudo apt update && sudo apt install nodejs npm -y
sudo npm install -g pm2
3. Creating the Process Manifest (ecosystem.config.js
Rather than passing flags manually on the CLI, define a declarative manifest in your project root:
module.exports = {
apps: [{
name: 'mermiko-discord-bot',
script: 'src/index.js',
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: '500M',
env: {
NODE_ENV: 'production'
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss'
}]
};
4. Launching & Enabling Systemd Startup
Deploy and persist your bot with three commands:
# Uruchomienie aplikacji z manifestu
pm2 start ecosystem.config.js
# Zapisanie bieżącej listy procesów
pm2 save
# Wygenerowanie i wdrożenie skryptu systemd
pm2 startup
You can inspect your bot's health and live logs anytime usingpm2 statusandpm2 logs mermiko-discord-bot.