EN · $ USD
Discord Bot Hosting

How to Run a discord.py Bot on a Linux Server with systemd

6 min read Updated: OyunBulut technical team

In short

To host a discord.py bot on a Linux server, run it as a separate user inside a Python virtual environment (venv) and store the token in a .env file. Then create a systemd service file and enable it with Restart=always. The bot starts automatically on boot, comes back within seconds if it crashes, and its logs can be followed with journalctl.

In this guide
  1. Before you start
  2. Why systemd instead of screen, tmux or nohup?
  3. 1. Prepare Python and the bot user
  4. 2. Transfer the code and create a virtual environment
  5. 3. Store the token in a .env file
  6. 4. Create the systemd service file
  7. 5. Enable and test the service
  8. 6. Follow the logs with journalctl
  9. 7. Update the bot
  10. A template service for multiple bots
  11. Common errors
  12. Next step: Move your bot to a permanent server

The most reliable way to run a discord.py bot 24/7 on a Linux server is to install it in a Python virtual environment and define it as a systemd service. systemd is the service manager built into every modern Linux distribution; it starts the bot on boot, restarts it if it crashes and writes all output to the system journal. You don't need to install any extra tools. The steps below are written for Ubuntu 22.04/24.04 and Debian 12.

Before you start

  • A Linux VDS with root access. For a single discord.py bot, the OB-DISCORD-1 bot VDS with 2 vCPU and 2 GB RAM is more than enough.
  • A bot token from the Discord Developer Portal.
  • Your discord.py project running on your computer, plus a requirements.txt file listing its dependencies.

We explain why you should move your bot off your own computer in What is Discord bot hosting. If you use Node.js, our discord.js and PM2 guide will be a better fit.

Why systemd instead of screen, tmux or nohup?

Many guides online suggest leaving the bot running in the background with screen or nohup. These keep the bot running after your SSH session closes, but they don't do the other jobs a 24/7 service needs.

Featurescreen / tmuxnohupsystemd
Keeps running after SSH closesYesYesYes
Automatic restart after a crashNoNoYes
Automatic start on bootNoNoYes
Central logs with timestampsNo, stays on screenWrites to a single fileFilterable with journald
Privilege restrictionNoNoPossible with the service file

screen is still handy for quick tests and live debugging; for permanent hosting, systemd is the right tool.

1. Prepare Python and the bot user

Connect over SSH as root, install the required packages and create a separate user to run the bot:

apt update && apt upgrade -y
apt install -y python3 python3-venv python3-pip git
adduser --disabled-password --gecos "" botuser
python3 --version

Not running the bot as root matters: a vulnerability in your code or in a library you use will then only affect the bot user's files.

2. Transfer the code and create a virtual environment

A virtual environment (venv) keeps a project's Python packages in a folder separate from the system. On Debian 12 and Ubuntu releases after 23.04, trying to install packages into the system Python with pip install gives you an externally-managed-environment error; a venv is the right fix.

su - botuser
git clone https://github.com/kullanici-adiniz/benim-botum.git
cd benim-botum
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

If you don't use Git, upload the files over SFTP to the /home/botuser/benim-botum folder and run chown -R botuser:botuser /home/botuser/benim-botum as root. Don't copy the venv or __pycache__ folders from your computer; the virtual environment should be recreated on each machine.

A minimal requirements.txt looks like this:

discord.py
python-dotenv

If your bot joins voice channels and plays music, install voice support and FFmpeg too:

pip install -U "discord.py[voice]"
exit
apt install -y ffmpeg

3. Store the token in a .env file

Create a .env file in the project folder as the bot user and restrict its permissions:

nano /home/botuser/benim-botum/.env
chmod 600 /home/botuser/benim-botum/.env
DISCORD_TOKEN=buraya_bot_tokeniniz

Because systemd reads this file through EnvironmentFile, write each line as ANAHTAR=değer (KEY=value); don't prefix lines with export. Always add the .env file to your .gitignore. A simple example that reads the token from an environment variable:

import os
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f"Giriş yapıldı: {bot.user}")

@bot.command()
async def ping(ctx):
    await ctx.send(f"Pong! {round(bot.latency * 1000)} ms")

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

message_content is a privileged intent; if you enable it in code, you also need to enable it on the Bot tab in the Developer Portal. Otherwise the bot shuts down with a PrivilegedIntentsRequired error.

Before setting up the service, test the bot manually once, confirm it shows as online in Discord and stop it with Ctrl+C:

cd ~/benim-botum
set -a; source .env; set +a
.venv/bin/python bot.py

4. Create the systemd service file

As root, create the file /etc/systemd/system/discord-bot.service:

nano /etc/systemd/system/discord-bot.service
[Unit]
Description=Discord botu (discord.py)
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=10

[Service]
Type=simple
User=botuser
Group=botuser
WorkingDirectory=/home/botuser/benim-botum
EnvironmentFile=/home/botuser/benim-botum/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/home/botuser/benim-botum/.venv/bin/python bot.py
Restart=always
RestartSec=10
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full

[Install]
WantedBy=multi-user.target

What the key lines mean:

  • After / Wants network-online.target: The bot won't try to start before the network connection is ready.
  • ExecStart: Points directly to the Python interpreter inside the virtual environment. That way you don't need source activate, and packages load from the right place.
  • EnvironmentFile: Passes the token from the .env file as an environment variable. Since systemd reads the file with root privileges, the 600 permission isn't a problem.
  • PYTHONUNBUFFERED=1: Writes Python output to the journal immediately without buffering, so logs don't show up late.
  • Restart=always and RestartSec=10: No matter why the bot stops, it's restarted after 10 seconds. If you only want restarts after failed exits, use Restart=on-failure.
  • StartLimitIntervalSec and StartLimitBurst: If the bot crashes 10 times within 300 seconds, systemd gives up. This stops a broken update from hammering Discord with endless login attempts.
  • NoNewPrivileges, PrivateTmp, ProtectSystem: Basic hardening settings that limit the service's privileges.

5. Enable and test the service

systemctl daemon-reload
systemctl enable --now discord-bot
systemctl status discord-bot

enable makes it start on boot, and --now starts the service right away. You should see active (running) in the status output. To test automatic restart, force-kill the process; the bot should come back in about 10 seconds:

systemctl kill -s SIGKILL discord-bot
sleep 12
systemctl status discord-bot

Finally, reboot the server with reboot and confirm the bot comes online on its own. If you change the service file later, run systemctl daemon-reload first and then systemctl restart discord-bot; otherwise systemd keeps running with the old settings. Use systemctl stop to stop the service temporarily, and systemctl disable to turn off starting on boot entirely.

6. Follow the logs with journalctl

systemd writes all of the bot's output to the journald journal. discord.py's default log output lands there too.

journalctl -u discord-bot -f
journalctl -u discord-bot --since "1 hour ago"
journalctl -u discord-bot -n 200 --no-pager

-f follows logs live, --since filters by time and -n shows the last lines.

7. Update the bot

su - botuser
cd ~/benim-botum
git pull
.venv/bin/pip install -r requirements.txt
exit
systemctl restart discord-bot

A template service for multiple bots

If you'll run several discord.py bots on the same server, you can use systemd's template unit feature instead of copying a separate service file for each one. The @ sign in the file name passes the name given when starting the service into the %i variable. Assume each bot has its own virtual environment, bot.py and .env file in a /home/botuser/BOT_ADI folder. In the /etc/systemd/system/discord-bot@.service file, only these lines change:

WorkingDirectory=/home/botuser/%i
EnvironmentFile=/home/botuser/%i/.env
ExecStart=/home/botuser/%i/.venv/bin/python bot.py

Then each bot is enabled with a single command, and its logs can be followed separately:

systemctl daemon-reload
systemctl enable --now discord-bot@moderasyon
systemctl enable --now discord-bot@muzik
journalctl -u discord-bot@muzik -f

With this method, even if you manage ten bots, you only need to update a single service file.

Common errors

ErrorCauseFix
status=203/EXECThe ExecStart path is wrong or the venv doesn't existVerify the path with ls and recreate the venv
status=217/USERThe user in the User= line doesn't existFix the username
ModuleNotFoundError: discordPackages were installed outside the venv or the system Python is runningInstall packages with .venv/bin/pip
KeyError: 'DISCORD_TOKEN'.env isn't being read or the variable name is differentCheck the EnvironmentFile path and the line format
PrivilegedIntentsRequiredThe intent is disabled in the portalEnable the intent in the Developer Portal
Service keeps restartingA startup error in the codeRead the first error with journalctl -u discord-bot -n 50

If your bot drops at regular intervals, work through the checks in our Discord bot keeps going offline guide. For details on systemd options, see the official systemd.service documentation.

Next step: Move your bot to a permanent server

This setup works exactly the same on any Linux VDS with root access. OyunBulut's OB-DISCORD-1 plan, with 2 vCPU, 2 GB RAM, 30 GB NVMe, KVM virtualization, layered DDoS protection, automatic setup and root access, is a good starting point for discord.py bots. If you'll run multiple bots, a database or a music stack on the same machine, you can compare the Discord Bot VDS plans and pick one with more RAM.

Frequently asked questions

Should I use systemd or screen for a discord.py bot?

Use systemd. A screen or tmux session doesn't restart the bot when it crashes and doesn't start it on its own when the server reboots; systemd handles both automatically.

Why do I get the externally-managed-environment error?

Debian 12 and newer Ubuntu releases block installing packages into the system Python with pip. Create a virtual environment for your project with python3 -m venv and install packages inside it.

What's the difference between Restart=always and Restart=on-failure?

Restart=always restarts the bot no matter why it stopped. Restart=on-failure only restarts it after failures, such as exiting with an error code or an unexpected signal.

How do I see my discord.py bot's logs?

The journalctl -u discord-bot -f command shows the logs live. If you set PYTHONUNBUFFERED=1 in the environment variables, print output shows up without delay.

Can I run multiple discord.py bots on the same server?

Yes. Just create a separate folder, a separate virtual environment and a differently named systemd service file for each bot. Plan your total RAM based on the number of bots.

For this guide

Recommended plans

Because OB-DISCORD-1 is a Linux VDS with root access, you can set up the Python virtual environment and systemd service exactly as in this guide and run your bot 24/7.

OB-DISCORD-1

Recommended

2 GB RAM

$1.96/mo

+VAT

  • Processor2 vCPU
  • ModelAMD Ryzen / Intel
  • Disk30 GB NVMe
  • LocationIstanbul
  • Port: 1G Port
  • Traffic: Fair use
  • Virtualization: KVM
  • Multi-layer DDoS protection

3 GB RAM

$2.26/mo

+VAT

  • Processor4 vCPU
  • ModelAMD Ryzen / Intel
  • Disk35 GB NVMe
  • LocationIstanbul
  • Port: 1G Port
  • Traffic: Fair use
  • Virtualization: KVM
  • Multi-layer DDoS protection

4 GB RAM

$2.55/mo

+VAT

  • Processor4 vCPU
  • ModelAMD Ryzen / Intel
  • Disk40 GB NVMe
  • LocationIstanbul
  • Port: 1G Port
  • Traffic: Fair use
  • Virtualization: KVM
  • Multi-layer DDoS protection

Discord Bot VDS — tüm paketler

Need help with setup?

Send questions about your service in a support ticket, and our technical team will walk you through it step by step.