Deployment
Deployment Guide
This guide will help you deploy your Discord bot to various hosting platforms and ensure it runs reliably in production.
Table of Contents
- Prerequisites
- Preparing for Production
- Deployment Options
- Production Best Practices
- Monitoring and Maintenance
- Updating Your Bot
Prerequisites
Before deploying your bot, make sure you have:
- A functioning Discord bot with a valid token
- All environment variables set up (check
.env.example
) - Tested your bot thoroughly in a development environment
- Basic understanding of your chosen hosting platform
Preparing for Production
1. Environment Configuration
Create production-specific environment settings:
# Production Environment
USE_SHARDING = true
TOKEN = "your-bot-token"
SHOW_DEBUG = false # Disable debug logs in production
PREFIX = -
2. Setup Process Manager
Install PM2 to ensure your bot stays running:
npm install pm2 -g
Create a PM2 ecosystem file for your bot:
# Create ecosystem.config.js
cat > ecosystem.config.js << 'EOL'
module.exports = {
apps: [{
name: "discord-bot",
script: "./dist/index.js",
env: {
NODE_ENV: "production",
},
instances: 1,
autorestart: true,
watch: false,
max_memory_restart: "1G",
env_production: {
NODE_ENV: "production"
}
}]
}
EOL
3. Build for Production
npm run build
Deployment Options
VPS Deployment
Deploying to a VPS (Virtual Private Server) gives you the most control over your bot's environment.
Step 1: Set up a VPS
Get a VPS from providers like:
- DigitalOcean
- Linode
- AWS EC2
- OVH
Step 2: Install Dependencies
# Update system packages
sudo apt update && sudo apt upgrade -y
# Install Node.js and npm
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
# Install Git
sudo apt install -y git
# Verify installations
node -v
npm -v
git --version
Step 3: Clone and Setup
# Clone your repository
git clone https://github.com/yourusername/discord-bot.git
cd discord-bot
# Install dependencies
npm install --production
# Create environment file
cp .env.example .env
nano .env # Edit with your production values
Step 4: Start with PM2
# Install PM2 globally
npm install pm2 -g
# Build the project
npm run build
# Start with PM2
pm2 start ecosystem.config.js --env production
# Make PM2 startup on system boot
pm2 startup
pm2 save
Railway
Railway provides a simple platform for deploying Node.js applications with ease.
Step 1: Connect Repository
- Create an account at Railway
- Create a new project and select "Deploy from GitHub repo"
- Connect your GitHub account and select your bot repository
Step 2: Configure Environment
- Go to the "Variables" tab
- Add all required environment variables:
TOKEN
USE_SHARDING
SHOW_DEBUG
PREFIX
NODE_ENV=production
Step 3: Configure Build Settings
- Go to the "Settings" tab
- Set the build command:
npm run build
- Set the start command:
node dist/index.js
Your bot will automatically deploy and stay online.
Heroku
Heroku is another popular platform for hosting Discord bots.
Step 1: Install Heroku CLI
# Install Heroku CLI
curl https://cli-assets.heroku.com/install.sh | sh
# Login to Heroku
heroku login
Step 2: Prepare Your App
Add a Procfile
to tell Heroku how to run your bot:
# Procfile
worker: node dist/index.js
Ensure your package.json has the proper build script and engine information:
{
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"heroku-postbuild": "npm run build"
}
}
Step 3: Create and Deploy
# Create Heroku app
heroku create your-bot-name
# Add environment variables
heroku config:set TOKEN=your_discord_token
heroku config:set USE_SHARDING=true
heroku config:set SHOW_DEBUG=false
heroku config:set PREFIX=-
# Deploy to Heroku
git push heroku main
# Ensure the worker is running (not web)
heroku ps:scale web=0 worker=1
DigitalOcean App Platform
DigitalOcean App Platform is a PaaS solution that makes deployment straightforward.
Step 1: Create a New App
- Go to DigitalOcean App Platform
- Create an account if you don't have one
- Click "Create App" and connect to your GitHub repository
Step 2: Configure the App
- Select the repository and branch
- Configure build settings:
- Build Command:
npm run build
- Run Command:
node dist/index.js
- Build Command:
- Add environment variables in the "Environment Variables" section
- Select appropriate resource plan (Basic is usually sufficient)
Step 3: Deploy
- Review your settings
- Click "Launch App"
- Monitor the build and deployment logs
Replit
Replit offers free hosting with some limitations.
Step 1: Create a Replit
- Sign up at Replit
- Create a new Repl and select "Import from GitHub"
- Import your Discord bot repository
Step 2: Configure Environment
- Create a
.replit
file:
run = "npm run start"
- Set up environment variables in the Secrets tab:
- Add all your environment variables from
.env.example
- Add all your environment variables from
Step 3: Keep Alive
To prevent your bot from going to sleep, add a simple web server:
// Add to index.ts
import express from 'express';
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Bot is alive!');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
Then use an uptime monitoring service like UptimeRobot to ping your bot regularly.
Docker Deployment
Docker allows you to containerize your bot for consistent deployment across environments.
Step 1: Create a Dockerfile
# Dockerfile
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
CMD ["node", "dist/index.js"]
Step 2: Build and Run Docker Image
# Build docker image
docker build -t discord-bot .
# Run docker container
docker run -d \
--name discord-bot \
--restart unless-stopped \
-e TOKEN=your_discord_token \
-e USE_SHARDING=true \
-e SHOW_DEBUG=false \
-e PREFIX=- \
discord-bot
Step 3: Docker Compose (Optional)
For easier management, create a docker-compose.yml:
version: '3'
services:
discord-bot:
build: .
restart: unless-stopped
environment:
- TOKEN=your_discord_token
- USE_SHARDING=true
- SHOW_DEBUG=false
- PREFIX=-
Then run with:
docker-compose up -d
Production Best Practices
Security
- Keep Tokens Secret: Never commit tokens to version control
- Limit Permissions: Give your bot only the permissions it needs
- Validate User Input: Always sanitize and validate inputs
- Use Environment Variables: Store sensitive information in environment variables
Performance
- Memory Management: Monitor and optimize memory usage
- Efficient Caching: Cache frequently used data, but expire old entries
- Rate Limiting: Implement rate limiting for commands to prevent abuse
- Proper Sharding: Use sharding for bots in many servers (>2500)
Reliability
- Error Handling: Implement comprehensive error handling
- Graceful Shutdown: Handle process termination gracefully
- Auto-Restart: Configure your process manager to restart on crashes
- Connection Recovery: Reconnect automatically if the connection drops
Monitoring and Maintenance
Logging
Implement comprehensive logging to track issues:
// Production logging setup
if (process.env.NODE_ENV === 'production') {
// Disable debug logging
client.logger.setLevel('info');
// Log to file
const logStream = fs.createWriteStream(path.join(__dirname, 'bot.log'), {flags: 'a'});
console.log = (...args) => {
const message = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg).join(' ');
logStream.write(`${new Date().toISOString()} - ${message}\n`);
};
}
Health Checks
Implement a basic health check endpoint:
app.get('/health', (req, res) => {
const health = {
uptime: process.uptime(),
message: 'OK',
timestamp: Date.now(),
shards: client.ws.shards.size,
ping: client.ws.ping
};
res.status(200).send(health);
});
Monitoring Options
- UptimeRobot: Free monitoring for basic uptime checks
- StatusCake: More advanced monitoring with alerts
- Prometheus + Grafana: For comprehensive metric collection and visualization
- Discord Webhook: Send status updates to a private Discord channel
Updating Your Bot
Planned Updates
- Prepare Changelog: Document what's changing
- Test in Staging: Test changes in a staging environment first
- Schedule Downtime: For major updates, schedule and announce downtime
- Deploy During Low Traffic: Update when fewer users are active
Emergency Updates
- Identify Issue: Quickly identify the root cause
- Hotfix: Create a minimal fix for the specific issue
- Testing: Test the hotfix in a staging environment if possible
- Deploy & Monitor: Deploy the fix and monitor for resolution
- Post-Mortem: Document what happened and how to prevent it
Rollback Plan
Always have a rollback plan in case an update causes issues:
# Using Git tags for versioning
git tag v1.0.0
# To roll back to a previous version
git checkout v0.9.0
npm run build
pm2 reload discord-bot
Following these deployment guidelines will help ensure your Discord bot runs reliably in production. Choose the hosting option that best fits your needs and budget, and always prioritize security and stability in your deployment process.