Skip to content

Offer: your first month of web hosting is free on monthly plans. Order by 7 Jan. See plans

HostEthical
All guides

Guides 18 min read ·

Discord Bot Hosting 24/7: Free Options vs a VPS, with a discord.js or discord.py Setup

How to host a Discord bot 24/7 in 2026: why free tiers sleep, how much VPS a bot needs, and discord.js (PM2) and discord.py (systemd) setup on Ubuntu 24.04.

To host a Discord bot 24/7, run it on an always-on Linux server, usually a small VPS, under a process manager such as PM2 or systemd that restarts it after a crash or a reboot. A bot keeps a permanent WebSocket connection open to Discord's Gateway, so free web tiers that go to sleep when nobody visits will knock it offline. Most bots are light: one modest VPS can run several of them, unless they play music or sit in thousands of servers.

This guide uses discord.js 14.28.1 on Node.js 26 (Active LTS) with PM2 7.1, and discord.py 2.7.1 on Python 3.12 with systemd, all on Ubuntu 24.04 LTS, as of November 2026.

Why does Discord bot hosting need to be 24/7?

A Discord bot logs in and opens a Gateway connection, a WebSocket that Discord pushes events through: messages, slash commands, members joining. The bot must keep sending heartbeats at an interval Discord sets, and if they stop arriving, Discord closes the connection. When the process stops, the bot shows as offline and commands fail until something starts it again.

There is one exception. A bot that only uses slash commands and buttons can receive them over HTTP instead, through an Interactions Endpoint URL. Discord then sends each interaction to your HTTPS address, and you must reply within 3 seconds. That kind of bot can run serverless, but it gets no message events and can't join voice. An app receives interactions one way or the other, never both.

Is free Discord bot hosting good enough?

For testing, sometimes. For a bot people rely on, the free tiers sleep, run out of credit or come with conditions:

OptionKeeps a Gateway bot online?The catch (checked November 2026)
Render, free web serviceNoSpins down after 15 minutes without inbound HTTP requests or WebSocket messages. Our reading: a bot's Gateway connection is one the bot opens to Discord, not inbound traffic, so it won't keep the service awake. Background workers have no free instances; the cheapest is US$7 a month (about ₹649 at ₹92.7 to the dollar) for 512 MB
Railway, Free planNot for longUS$1 of usage a month. Railway sleeps a service only after 5 to 10 minutes without outbound traffic, so a bot's heartbeats should keep it awake, but at Railway's published US$10 per GB of RAM a month, our arithmetic says US$1 covers only about 100 MB for a month, before any CPU
Oracle Cloud Always FreeYes, if you can get oneTwo small AMD VMs (1/8 OCPU and 1 GB each) plus Arm capacity of 2 OCPUs and 12 GB in total, home region only, and Oracle warns of "out of host capacity" errors when free shapes run out. Instances whose CPU (95th percentile), network and (on Arm) memory stay under 20% for 7 days may be reclaimed, and a quiet bot can look that idle. See our free VPS guide
Google Cloud Free TierYes, a small oneOne e2-micro VM in Oregon, Iowa or South Carolina only (no India region qualifies), with 30 GB of disk and 1 GB of outbound data a month
Cloudflare Workers, freeNo (HTTP interactions only)100,000 requests a day and 10 ms of CPU per request. Discord has an official tutorial for slash-command bots

Avoid sites that host bots free if you upload your code and token: whoever runs the server can read the token, and Discord's Developer Terms make you responsible for keeping it confidential.

How much VPS does a Discord bot need?

Less than most people expect. These are our rules of thumb, based on how the libraries work rather than on benchmarks:

  • A slash-command or moderation bot is light. It mostly waits for events, so memory grows before CPU does.
  • Memory follows the cache. Libraries keep servers, channels, members and messages in memory. discord.py stores up to 1,000 messages by default (max_messages), and discord.js lets you cap caches with Options.cacheWithLimits and sweepers.
  • The Guild Members intent makes big servers expensive. With it on, discord.py downloads every member list before it reports ready, which its docs call "incredibly slow" for many servers.
  • Voice is where CPU goes. Each playing stream runs FFmpeg and Opus encoding in real time, so a music bot busy in many servers at once needs real cores.
  • Very large bots must shard. Each Gateway shard handles at most 2,500 servers, and Discord's docs say bots in 2,500 or more must shard. discord.js can do it in one process (shards: 'auto') or with its ShardingManager; discord.py has AutoShardedClient.

Measure rather than guess: after a day of normal use, pm2 status or systemctl status shows a bot's memory.

How to host a Node.js Discord bot on a VPS (discord.js and PM2)

These steps take a discord.js bot to a fresh Ubuntu 24.04 server. If you haven't set up SSH keys, updates and a sudo user yet, start with how to set up a VPS.

1. Create the application and copy the token

In the Developer Portal, create an application, open the Bot page and click Reset Token. Discord shows the token once, so copy it straight into a password manager. On the Installation page, give Guild Install the applications.commands and bot scopes and only the permissions your bot uses, such as Send Messages. The discord.js guide suggests a separate application and token for development.

2. Create a user for your bots

sudo useradd --create-home --shell /bin/bash bot
sudo -iu bot        # work as the bot user; type exit to go back

The account has no password; you switch to it from your admin account. A bug in the bot or a package then reaches only this user's files, not the whole server.

3. Install Node.js 26 and PM2

# as your admin (sudo) user
curl -fsSL https://deb.nodesource.com/setup_26.x -o nodesource_setup.sh
sudo -E bash nodesource_setup.sh
sudo apt install -y nodejs git
sudo npm install -g pm2
node -v

discord.js 14 needs Node.js 18 or newer and its guide recommends the latest LTS; Ubuntu's own nodejs package is the end-of-life version 18. discord.js 15, still in development in November 2026, already requires Node.js 24.17 or newer, so Node.js 26 keeps you ready. Our Node.js hosting guide explains the release lines.

4. Add the code and keep the token in a .env file

sudo -iu bot
git clone https://github.com/your-name/jsbot.git ~/jsbot
cd ~/jsbot
npm ci --omit=dev
# starting from scratch instead? mkdir ~/jsbot && cd ~/jsbot && npm init -y && npm install discord.js

touch .env
chmod 600 .env      # only the bot user can read it
nano .env           # add the line below, then save

DISCORD_TOKEN=paste-your-bot-token-here

Put .env and node_modules in your project's .gitignore before your first commit. A minimal bot.js that answers a /ping command:

// bot.js: a minimal discord.js 14 bot
const path = require('node:path');
const { Client, Events, GatewayIntentBits } = require('discord.js');

process.loadEnvFile(path.join(__dirname, '.env')); // puts DISCORD_TOKEN into process.env

const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // no privileged intents

client.once(Events.ClientReady, (c) => {
  console.log(`Logged in as ${c.user.tag}`);
});

client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  if (interaction.commandName === 'ping') {
    await interaction.reply(`Pong! Gateway heartbeat ${client.ws.ping} ms`);
  }
});

client.login(process.env.DISCORD_TOKEN);

Node.js reads the file itself with process.loadEnvFile(), so no dotenv package is needed. Register /ping with the discord.js guide's deploy-commands.js script, and rerun it only when command definitions change.

5. Run it with PM2, restart on crash and keep logs

Create ~/jsbot/ecosystem.config.cjs:

// ecosystem.config.cjs: safe to commit, the token stays in .env
module.exports = {
  apps: [
    {
      name: 'jsbot',
      script: 'bot.js',
      cwd: '/home/bot/jsbot',
      exec_mode: 'fork',               // one process; don't add an instances setting
      exp_backoff_restart_delay: 1000, // waits 1 s, 1.5 s, 2.25 s ... up to 15 s between crashes
      min_uptime: '30s',               // a run shorter than this counts as an unstable start
      max_restarts: 10,                // stop after 10 unstable starts (see the note below)
    },
  ],
};
pm2 start ecosystem.config.cjs
pm2 save                  # remember the running apps for the next boot
pm2 startup               # prints a "sudo env PATH=... pm2 startup systemd -u bot --hp /home/bot" line
exit                      # back to your admin user, then paste and run that line
sudo -iu bot
pm2 install pm2-logrotate # rotates logs at 10 MB, keeps 30 files
pm2 logs jsbot            # live logs; Ctrl+C stops watching

PM2 switches to cluster mode once instances is set, so set fork explicitly. Our reasoning for keeping one copy: a second process would open its own Gateway session with the same token, receive the same events and could act on them twice. The exponential backoff slows a crash loop down. The restart cap has a catch: PM2 7.1.2's source code only counts unstable starts during the first min_uptime × max_restarts after a start or pm2 restart, here 30 s × 10 = 5 minutes. So it catches a broken update straight after you restart, but a crash loop that begins later is only slowed, to a restart every 15 seconds or so. The security and monitoring sections explain why that matters.

6. Update the bot

sudo -iu bot
cd ~/jsbot && git pull && npm ci --omit=dev && pm2 restart jsbot
node deploy-commands.js   # only if you added or changed commands

Discord allows 200 command creates per day per server, so don't re-register commands on every start.

How to self host a discord.py bot with systemd

systemd is already on every Ubuntu server, so a Python bot needs no extra process manager. Our Telegram bot guide covers restart policies in more depth.

1. Create a virtual environment and install discord.py

sudo apt install -y python3-venv git
sudo -iu bot
mkdir ~/pybot && cd ~/pybot
python3 -m venv venv
venv/bin/pip install -U "discord.py>=2.7,<3"

discord.py 2.7.1 supports Python 3.8 or newer. Ubuntu 24.04 ships 3.12 and marks it as externally managed, so pip won't install packages system-wide; hence the venv.

2. Store the token

touch .env
chmod 600 .env
nano .env           # add the two lines below, then save

DISCORD_TOKEN=paste-your-bot-token-here
GUILD_ID=your-test-server-id

To copy the server ID, turn on Developer Mode under User Settings, Advanced, then right-click the server.

3. The bot code

# bot.py: a minimal discord.py 2.7 bot
import os

import discord
from discord import app_commands

TEST_GUILD = discord.Object(id=int(os.environ["GUILD_ID"]))


class Bot(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())  # no privileged intents
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        self.tree.copy_global_to(guild=TEST_GUILD)
        await self.tree.sync(guild=TEST_GUILD)  # commands appear in your test server at once


client = Bot()


@client.tree.command(description="Check that the bot is online")
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message(f"Pong! Gateway latency {client.latency * 1000:.0f} ms")


@client.event
async def on_ready():
    print(f"Logged in as {client.user}")


client.run(os.environ["DISCORD_TOKEN"])

This follows discord.py's app commands example; Intents.default() leaves out the privileged intents. Like the example, it syncs the commands to your test server every time the bot starts; once they settle, sync only when you change them, as with the discord.js script above.

4. Create the systemd service

Type exit to return to your admin user and create /etc/systemd/system/pybot.service:

[Unit]
Description=pybot Discord bot
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=1h
StartLimitBurst=10

[Service]
User=bot
Group=bot
WorkingDirectory=/home/bot/pybot
EnvironmentFile=/home/bot/pybot/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/home/bot/pybot/venv/bin/python bot.py
Restart=always
RestartSec=10
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now pybot
systemctl status pybot
sudo journalctl -u pybot -f        # live logs; -n 100 or --since today for older ones

systemd passes the .env values to the bot as environment variables. Restart=always brings the bot back 10 seconds after any exit, and the start limit gives up after 10 starts in an hour; once you've fixed the cause, run sudo systemctl reset-failed pybot and start it again. PYTHONUNBUFFERED=1 sends print() output to the journal straight away.

5. Update the bot

sudo -iu bot
cd ~/pybot && git pull && venv/bin/pip install -r requirements.txt
exit
sudo systemctl restart pybot
Give your bots a server that never sleeps. VPS Starter has 4 vCPU, 8 GB RAM and a dedicated IPv4, in Mumbai or Germany, billed in rupees. See VPS plans →

Can you run several Discord bots on one VPS?

Yes. Give each bot its own folder, its own Discord application and token, its own .env and one process. With PM2, list every bot in one ecosystem file and manage them all with pm2 status:

// /home/bot/ecosystem.config.cjs
const bot = (name, script) => ({
  name, script, cwd: `/home/bot/${name}`, exec_mode: 'fork',
  exp_backoff_restart_delay: 1000, min_uptime: '30s', max_restarts: 10,
});

module.exports = { apps: [bot('jsbot', 'bot.js'), bot('modbot', 'index.js')] };

With systemd, copy the unit file for each bot, or write one template unit, discord-bot@.service, with %i in place of the folder name, and start each bot with sudo systemctl enable --now discord-bot@pybot. If bots belong to different people, give each a separate Linux user so one can't read another's token. Containers are another way to keep bots apart; see Docker on a VPS.

What does a Discord music bot need?

Voice is the one job that makes a bot heavy: a voice bot also connects to a Discord voice server over UDP, converts audio with FFmpeg and encodes it as Opus. Discord's voice documentation says that from 1 March 2026 it supports only end-to-end encrypted calls using its DAVE protocol, so your library must support DAVE.

  • discord.js: @discordjs/voice 0.19.2 needs Node.js 22.12 or newer and includes @snazzah/davey for DAVE; add an Opus library and FFmpeg. @discordjs/opus has prebuilt binaries for Node.js 22, 24 and 26 on glibc 2.39 (Ubuntu 24.04); elsewhere it compiles and needs Python and a C/C++ toolchain.
  • discord.py: version 2.7.0 added DAVE. The discord.py[voice] extra brings PyNaCl and davey; add the system Opus library, FFmpeg, and the libffi, libnacl and python3-dev packages its install guide lists.
sudo apt install -y ffmpeg                       # FFmpeg 6.1 on Ubuntu 24.04

# discord.js bot, as the bot user in its folder
npm install @discordjs/voice @discordjs/opus

# discord.py bot
sudo apt install -y libopus0 libffi-dev libnacl-dev python3-dev
sudo -u bot /home/bot/pybot/venv/bin/pip install -U "discord.py[voice]>=2.7,<3"

Discord's docs say a voice client must be able to receive UDP packets. You don't need to open a port for that: ufw allows outgoing traffic by default and lets the replies back in. discord.py's FFmpegPCMAudio starts a separate FFmpeg process for each source, which is why CPU grows with the number of servers playing at once.

Discord sets a voice channel's region from the first person who joins the empty channel, unless someone with Manage Channels sets an override. Our reasoning from that: the voice server tends to follow your members, so if they're mostly in India, a bot in Mumbai is likely to be closer to it than one in Europe. Discord's FAQ doesn't list where its voice servers are, so treat this as a likely gain, not a measured one. For text bots, location matters less.

Play only audio you have the right to stream. Discord's Developer Terms say your app must not infringe third-party rights, including intellectual property, and that you must hold the rights needed to distribute the content your app provides. YouTube's Terms of Service, for example, forbid downloading or broadcasting its content except through YouTube's own features or with permission.

How do you keep a self-hosted Discord bot secure?

Never commit the token. Discord's docs say never to check it into version control, and its Developer Terms say credentials may not be embedded in open source projects. If a token leaks, click Reset Token on the Bot page, put the new one in .env and restart the bot.

Don't let a crash loop reset it for you. Discord allows 1,000 logins (IDENTIFY calls) per 24 hours. Hit that limit and Discord ends every session and resets the bot token. Each process restart is a fresh login, so a bot that logs in, crashes and restarts over and over could use up the allowance: at one restart every 15 seconds, our arithmetic says 1,000 logins take a little over four hours. The systemd start limit above stops after 10 starts in an hour. PM2's restart cap only covers the first five minutes after a start or restart, so with PM2 also watch the restart count in pm2 status and set up the outside alert in the next section. Discord also temporarily blocks IP addresses that make 10,000 invalid requests (401, 403 or 429 responses) in 10 minutes. On a VPS the dedicated IPv4 is yours alone, so only your own bot's mistakes count against it.

Request the fewest intents. Guild Presences, Guild Members and Message Content are privileged. Slash commands need none of them; Message Content matters only if the bot reads ordinary message text, such as prefix commands. Since 10 June 2026, Discord's review guide says apps seen by more than 10,000 unique users must apply for privileged intents (within 90 days of being notified) and reapply every year; before that, the trigger was 100 servers. Discord's own pages don't fully agree yet: the intents list on the Gateway page still says verified apps ("required for apps in 100+ guilds") need approval, while the June 2026 changelog says App Verification and intent review are now separate. Go by the newer 10,000-user rule and check what the Developer Portal shows for your app. Asking for an intent you haven't enabled in the portal closes the connection with error 4014, a common reason a new bot won't start.

Request the fewest permissions. Avoid Administrator, which allows every permission and bypasses channel overrides. Since 16 November 2026, Discord hides channel details from bots without View Channel, so grant that permission in the channels where the bot works.

Open no inbound ports. Gateway and voice connections are outbound, so a bot needs only SSH open:

sudo ufw allow 22/tcp
sudo ufw enable
sudo ufw status verbose

The exception is a bot that receives interactions over HTTP. It needs a public HTTPS endpoint that answers Discord's PING and checks the X-Signature-Ed25519 and X-Signature-Timestamp headers, so open ports 80 and 443 and put Nginx with a Let's Encrypt certificate in front, as in our Node.js hosting guide.

How do you monitor a Discord bot?

On the server, pm2 status and pm2 monit show uptime, restarts, CPU and memory, and systemctl status with journalctl does the same for systemd bots. Inside the bot, client.ws.ping (discord.js) and client.latency (discord.py) report the Gateway heartbeat round trip.

Those tools can't warn you when the whole server is down, so add an outside check. Healthchecks.io gives each check a ping URL and alerts you when a ping doesn't arrive on time; its free Hobbyist plan monitors 20 jobs. Have the bot ping it every minute while connected, set the check's period to one minute with a few minutes' grace, and keep the URL in .env: Healthchecks.io says to treat it as a secret.

// discord.js: add to bot.js
setInterval(() => {
  if (client.isReady() && process.env.HEALTHCHECK_URL) {
    fetch(process.env.HEALTHCHECK_URL).catch(() => {});
  }
}, 60_000);
# discord.py: add to bot.py above client.run(), and call healthcheck.start() at the end of setup_hook
import aiohttp
from discord.ext import tasks

@tasks.loop(minutes=1)
async def healthcheck():
    url = os.environ.get("HEALTHCHECK_URL")
    if url and client.is_ready():
        async with aiohttp.ClientSession() as session:
            async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)):
                pass

If the process crashes for good, hits its restart limit or the server goes offline, the pings stop and you get an email.

Running Discord bots on HostEthical

On HostEthical, bots belong on a Cloud VPS: unmanaged KVM with full root access, a dedicated IPv4 address, SSD storage and Ubuntu 24.04 LTS among the OS choices, built automatically after payment, usually within 5 to 15 minutes. Plans start at ₹860 a month, or about ₹774.17 a month when billed yearly. You pay in rupees by UPI or binance Pay (USDT), with no dollar card charges, and the price stays the same at renewal.

PlanvCPURAMStoragePaid monthlyPaid up front, per monthAt renewal
VPS Starter4 cores8 GB100 GB SSD₹860₹774.17 (yearly)Same price
VPS Pro6 cores12 GB200 GB SSD₹1,170₹1,053.33 (yearly)Same price
VPS Max8 cores24 GB300 GB SSD₹2,190₹1,971.67 (yearly)Same price

VPS Starter's 4 vCPU and 8 GB RAM is enough for several typical bots side by side, plus their database. Move to VPS Pro or Max for a music bot busy in many servers, a sharded bot, or heavier apps on the same server. Our web hosting is built for websites and web apps that answer HTTP requests; production bots belong on the VPS, where you control the process, the versions and the restart policy.

Choose Mumbai for a voice bot whose members are mostly in India: as explained in the music bot section, it is likely to sit closer to the voice server Discord picks for them. Mumbai also keeps the bot's own files and database in India, for ₹380 a month more than Germany. For a text or slash-command bot, every message passes through Discord's servers either way, so location matters less and Germany is the cheaper choice. Our guide to VPS hosting in Mumbai covers the trade-off. If you add a web dashboard or an HTTP interactions endpoint, register a domain with us and point its A record at the VPS with our nameservers and DNS editor.

Host your Discord bots this week. Pick VPS Starter in Mumbai or Germany, pay by UPI, and follow the steps above. See Cloud VPS →

Frequently asked questions

Can I host a Discord bot for free 24/7?

Not reliably. As of November 2026, Render's free web services spin down after 15 minutes without inbound traffic and its background workers have no free instances, Railway's Free plan includes only US$1 of usage a month, and Oracle Cloud can reclaim Always Free VMs that look idle for 7 days. A bot that only uses slash commands can run on Cloudflare Workers' free plan over HTTP, but a bot that needs the Gateway, message events or voice needs an always-on server.

Does a Discord bot need open ports or a public IP address?

Not a normal Gateway bot. It connects out to Discord over a WebSocket, and voice uses outgoing UDP whose replies ufw lets back in, so a firewall that allows only SSH is enough. The exception is a bot that receives interactions through an Interactions Endpoint URL: Discord must reach it over HTTPS, so it needs ports 80 and 443 open, a public address and a TLS certificate.

What should I do if my Discord bot token leaks?

Reset it straight away on the Bot page of the Discord Developer Portal, which issues a new token, then put the new token in the bot's .env file and restart the bot. If the token was ever committed to Git, treat it as public even after you delete the commit, because old history, forks and clones can still contain it. Discord also resets a token itself when the bot reaches its limit of 1,000 logins (IDENTIFY calls) in 24 hours, which a crash loop can cause.

When does a Discord bot need sharding?

Discord's Gateway documentation says each shard can handle at most 2,500 servers and that bots in 2,500 or more servers must shard. discord.js can run several shards in one process with shards: 'auto' or spread them across processes with its ShardingManager, and discord.py has AutoShardedClient. Below that size, one Gateway connection is enough.

Should I use discord.js or discord.py for a bot I want to self-host?

Use the language you know better, because hosting works the same way for both: an always-on process under PM2 or systemd. As of November 2026, discord.js 14.28.1 needs Node.js 18 or newer (Node.js 26 LTS is a good choice) and discord.py 2.7.1 supports Python 3.8 or newer. Both can join voice with Discord's DAVE end-to-end encryption, through the discord.js voice package 0.19 and discord.py's voice extra.