Host a Discord bot on a VPS with systemd or pm2
Running a bot in a terminal stops when you log out. A process manager keeps it alive, restarts it if it crashes and starts it at boot. Below are two common options. Commands target Ubuntu and Debian and may differ elsewhere.
Prepare the bot
- Install runtimes, for example sudo apt install nodejs npm -y or sudo apt install python3 python3-venv -y
- Copy your bot to a folder such as /home/deploy/mybot
- Install dependencies with npm install, or create a venv and run pip install -r requirements.txt
- Keep your token in an environment file, never in public code
Option 1: systemd
systemd is built into most Linux systems, so nothing extra is needed.
- sudo nano /etc/systemd/system/mybot.service
- Paste a unit like this:
[Unit]
Description=My Discord bot
After=network-online.target
[Service]
User=deploy
WorkingDirectory=/home/deploy/mybot
EnvironmentFile=/home/deploy/mybot/.env
ExecStart=/usr/bin/node index.js
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
- sudo systemctl daemon-reload
- sudo systemctl enable --now mybot
- sudo systemctl status mybot
For Python, change ExecStart to something like /home/deploy/mybot/venv/bin/python bot.py.
View logs
- journalctl -u mybot -f follows live logs
- journalctl -u mybot -n 100 shows the last 100 lines
Option 2: pm2 for Node.js
- sudo npm install -g pm2
- pm2 start index.js --name mybot
- pm2 save
- pm2 startup, then run the command it prints
Useful commands are pm2 list, pm2 logs mybot, pm2 restart mybot and pm2 stop mybot.
Which should you choose
- systemd suits any language and needs no extra install
- pm2 is quick and friendly for Node.js bots
Tips
- Check the path of node with which node before writing the unit
- Rotate or limit logs so the disk does not fill
- After code changes, restart with sudo systemctl restart mybot
- Make sure your bot enables the right intents in the Discord developer portal
Your VPS stays up 24/7 on Tabi Cloud, and our team can help via Discord ticket or email.