On this page
- What does a bot server need?
- How do you create the bot application and token?
- How do you write a minimal bot?
- Where should the token live?
- How do you register slash commands?
- How do you run the bot with systemd?
- How do PM2 and Docker compare as alternatives?
- How do you update the bot and fix common errors?
- Questions
What does a bot server need?
Very little. A discord.js bot keeps one outgoing WebSocket connection to the Discord gateway and makes HTTPS calls to its API. It does not listen on any port, so you open nothing in the firewall beyond SSH. A small bot serving a few servers runs well in a few hundred megabytes of RAM; memory grows with the number of guilds and with what the bot caches.
Prepare a Linux user that will own the bot, and install a current Node.js LTS as described on installing Node.js and npm. discord.js 14 requires Node.js 18 or newer, and the env-file flag used below needs Node.js 20.6 or later.
sudo adduser --disabled-password --gecos "" discordbot # Ubuntu, Debian
sudo useradd -m discordbot # Rocky, Alma
node -vHow do you create the bot application and token?
In the Discord developer portal create a new application, open the Bot section and reset the token to reveal it. Copy it once and keep it private: anyone holding the token controls the bot. While you are there, enable only the privileged gateway intents your code really uses (Message Content, Server Members, Presence); a bot that only answers slash commands needs none of them.
Under OAuth2, build an invite link with the bot and applications.commands scopes and the permissions your bot needs, then open it to add the bot to a test server. Copy the application ID (client ID) and the test server ID as well; you will need both to register commands.
How do you write a minimal bot?
Switch to the bot user, create the project and install discord.js.
sudo -iu discordbot
mkdir -p ~/bot && cd ~/bot
npm init -y
npm install discord.jsSave this as index.js. It answers a /ping command with the gateway latency:
const { Client, Events, GatewayIntentBits } = require("discord.js");
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
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: ${client.ws.ping} ms`);
}
});
process.on("SIGTERM", () => { client.destroy(); process.exit(0); });
client.login(process.env.DISCORD_TOKEN);The SIGTERM handler lets the bot leave the gateway cleanly when systemd or Docker stops it.
Where should the token live?
In an environment file next to the code, owned by the bot user and closed to everyone else. Never commit it, and never paste it into a chat or ticket.
cat > ~/bot/.env <<'EOF'
DISCORD_TOKEN=paste-the-token-here
CLIENT_ID=123456789012345678
GUILD_ID=876543210987654321
EOF
chmod 600 ~/bot/.env
echo ".env" >> ~/bot/.gitignoreUse plain KEY=value lines without quotes or export. That format is read by the Node.js --env-file flag, by systemd EnvironmentFile and by Docker Compose alike. If the token ever leaks, reset it in the portal immediately; the old one stops working at once. More on handling variables is in working with environment variables.
How do you register slash commands?
Slash commands are registered once through the REST API, not on every start. A small script does it; guild commands appear instantly in the test server, while global commands can take a while to spread.
const { REST, Routes, SlashCommandBuilder } = require("discord.js");
const commands = [
new SlashCommandBuilder().setName("ping").setDescription("Check latency").toJSON(),
];
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands }
).then(() => console.log("commands registered"));Save it as deploy-commands.js and run it, then start the bot by hand to test:
node --env-file=.env deploy-commands.js
node --env-file=.env index.jsWhen the console prints the login line, type /ping in the test server. Stop the bot with Ctrl+C and move on to running it as a service.
How do you run the bot with systemd?
A unit file gives you restarts, boot start and logs in the journal with no extra software. Exit the bot user shell and, as your sudo user, create /etc/systemd/system/discordbot.service:
[Unit]
Description=discord.js bot
After=network-online.target
Wants=network-online.target
[Service]
User=discordbot
WorkingDirectory=/home/discordbot/bot
EnvironmentFile=/home/discordbot/bot/.env
ExecStart=/usr/bin/node index.js
Restart=always
RestartSec=5
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
PrivateTmp=true
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now discordbot
journalctl -u discordbot -fThe hardening lines make the file system read-only for the bot. If your bot writes data, add ReadWritePaths=/home/discordbot/bot/data. Check the node path with command -v node; with nvm, use the full path from nvm which as explained in the nvm guide.
How do PM2 and Docker compare as alternatives?
PM2 is a good fit if the same user already runs other Node.js processes. Start the bot with the env file passed to Node, then save the list:
pm2 start index.js --name discordbot --node-args="--env-file=.env"
pm2 saveThe boot setup is on the PM2 page. Docker suits you when the server already runs containers or you want identical builds everywhere. With Docker Engine installed (see the Docker Engine tutorial), add a Dockerfile and a compose.yaml:
FROM node:24-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
CMD ["node", "index.js"]services:
bot:
build: .
env_file: .env
restart: unless-stoppedRun docker compose up -d --build and follow the output with docker compose logs -f bot. Add .env to a .dockerignore file so the token is not copied into the image.
How do you update the bot and fix common errors?
Pull new code, install dependencies and restart:
cd /home/discordbot/bot
sudo -u discordbot git pull
sudo -u discordbot npm ci --omit=dev
sudo systemctl restart discordbot- Used disallowed intents: the code requests a privileged intent that is switched off in the portal. Enable it there or remove it from the code.
- An invalid token was provided: the token was reset or the env file has quotes or spaces. Paste it again as a bare value.
- Command does not appear: rerun the registration script, and check that the invite link included the
applications.commandsscope. - Bot goes offline at night: look for crashes with
journalctl -u discordbot --since yesterday; unhandled promise rejections end the process on current Node.js lines.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about Host a discord.js bot
Does a Discord bot need any open ports?
No. It only makes outgoing connections to Discord, so keep the firewall closed except for SSH.
How much does a small bot use?
A bot in a handful of servers usually stays in the low hundreds of megabytes of RAM and barely touches the CPU. Large bots with many guilds need more memory for caches.
Is it safe to keep the token in an env file?
Yes, if the file belongs to the bot user with mode 600 and is excluded from git and Docker images. Reset the token at once if it ever leaks.
Can one server host more than one bot?
Yes. Give each bot its own folder, env file and service name, such as discordbot-music and discordbot-mod.
Should I use systemd or PM2?
Either is fine. systemd needs no extra software and adds sandboxing options; PM2 is handy when you already manage several Node apps with it.