Discord bot stops running after SSH disconnect on cloud server

I’m having trouble keeping my Discord bot running on a cloud VM instance. When I connect via SSH and start the bot using node index.js, everything works fine initially. However, once I close the SSH session, the bot process terminates automatically after a few minutes.

Here’s what I’m currently doing:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on('ready', () => {
  console.log('Bot is online!');
});

client.login('YOUR_BOT_TOKEN');

I need the bot to continue running even after I disconnect from SSH. What’s the best approach to keep the process alive permanently on the server?

yeah, pm2’s solid but you can also just use nohup node index.js & if u want something simpler. the nohup command keeps it running after u disconnect from ssh and & puts it in the background. just remember to save the process id in case u need to kill it later.

This is a common issue since your bot process is linked to the SSH session, which causes it to terminate upon disconnection. A good solution is to use PM2. Install it globally with npm install -g pm2, and then run your bot using pm2 start index.js --name discord-bot. This will ensure that your bot continues to run even after you close the SSH session. Additionally, PM2 provides features like automatic restarts if the bot crashes and the ability to view logs with pm2 logs. It’s also convenient for managing startup scripts so your bot will automatically restart after a server reboot.