-
Notifications
You must be signed in to change notification settings - Fork 0
16. Docker Automated Setup Guide
This guide covers the automated Docker setup process for deploying Utils Bot Plus in production environments, specifically designed for non-interactive hosting services like Render, Railway, and Heroku.
- Overview
- Prerequisites
- Automated Setup Script
- Production Docker Configuration
- Environment Variables
- Health Check Integration
- Non-Interactive Deployment
- Verification and Testing
- Troubleshooting
The automated Docker setup provides a streamlined, non-interactive deployment process that:
- Automatically generates required environment variables
- Creates optimized production Docker images
- Integrates health checks for hosting services
- Supports multiple hosting platforms
- Provides deployment verification tools
Before using the automated setup, ensure you have:
- Docker installed and running
- Git repository cloned
- Discord bot token from Discord Developer Portal
- Target hosting service account (Render, Railway, or Heroku)
The docker-setup.sh
script handles the complete setup process:
# Make the script executable
chmod +x docker-setup.sh
# Run the automated setup
./docker-setup.sh
- Environment Validation: Checks for required environment variables
-
Automatic Generation: Creates missing variables like
SECRET_KEY
-
Directory Setup: Creates necessary directories (
logs/
,data/
) - Database Initialization: Sets up SQLite database structure
- Docker Image Build: Creates production-ready Docker image
- Verification: Runs deployment readiness checks
- Non-Interactive Mode: No user input required during execution
- Error Handling: Comprehensive error detection and reporting
- Logging: Detailed setup progress logging
- Rollback Support: Safe failure handling
The production Dockerfile uses a multi-stage build process:
# Stage 1: Builder
FROM python:3.11-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
# Stage 2: Production
FROM python:3.11-slim as production
# Security and optimization configurations
RUN groupadd -r botuser && useradd -r -g botuser botuser
WORKDIR /app
COPY --from=builder /root/.local /home/botuser/.local
COPY . .
RUN chown -R botuser:botuser /app
USER botuser
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:${PORT:-8080}/health || exit 1
CMD ["python", "main_hosted.py"]
- Multi-Stage Build: Reduces final image size
- Non-Root User: Enhanced security
- Health Checks: Built-in monitoring
- Environment Flexibility: Dynamic port configuration
# Core Bot Configuration
DISCORD_TOKEN=your_discord_bot_token_here
SECRET_KEY=auto_generated_32_char_key
# Database Configuration
DATABASE_URL=sqlite:///data/bot.db
# Hosting Service Configuration
PORT=8080 # Auto-detected by hosting services
# Feature Toggles
ENABLE_WEB_SERVER=true
ENABLE_HEALTH_CHECKS=true
LOG_LEVEL=INFO
# Security Settings
ALLOWED_HOSTS=*
CORS_ORIGINS=*
# Performance Settings
MAX_WORKERS=4
TIMEOUT=30
The setup script automatically generates:
-
SECRET_KEY
: 32-character cryptographically secure key -
DATABASE_URL
: SQLite database path -
PORT
: Default port configuration
The bot includes a web server with health check endpoints:
-
/health
: Basic health status -
/ready
: Readiness probe for containers -
/
: Simple status page
from aiohttp import web
import asyncio
async def health_check(request):
return web.json_response({
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"bot_status": "connected" if bot.is_ready() else "connecting"
})
async def readiness_check(request):
if bot.is_ready():
return web.json_response({"status": "ready"})
else:
return web.json_response({"status": "not_ready"}, status=503)
-
Render: Uses
/health
for health checks -
Railway: Monitors
/ready
endpoint -
Heroku: Checks
/
for basic connectivity
The system automatically detects hosting environments:
def detect_hosting_service():
if os.getenv('RENDER'):
return 'render'
elif os.getenv('RAILWAY_ENVIRONMENT'):
return 'railway'
elif os.getenv('DYNO'):
return 'heroku'
else:
return 'docker'
Each hosting service has optimized configurations:
services:
- type: web
name: utils-bot-plus
env: docker
dockerfilePath: ./Dockerfile.prod
healthCheckPath: /health
envVars:
- key: DISCORD_TOKEN
sync: false
- key: PORT
value: 10000
{
"build": {
"builder": "dockerfile",
"dockerfilePath": "Dockerfile.prod"
},
"deploy": {
"healthcheckPath": "/ready",
"healthcheckTimeout": 30
}
}
web: python main_hosted.py
The verify_deployment.py
script checks deployment readiness:
python verify_deployment.py
- Environment Variables: Validates all required variables
- File Structure: Ensures all necessary files exist
- Database Connection: Tests database connectivity
- Bot Initialization: Verifies bot can start
- Health Endpoints: Tests web server functionality
The script provides detailed results:
✅ Environment Variables: OK
✅ File Structure: OK
✅ Database Connection: OK
✅ Bot Initialization: OK
✅ Health Endpoints: OK
🚀 Deployment Ready!
# Fix file permissions
chmod +x docker-setup.sh
sudo chown -R $USER:$USER .
# Clean Docker cache
docker system prune -f
docker build --no-cache -f Dockerfile.prod -t utils-bot-plus .
# Regenerate environment file
rm .env
./docker-setup.sh
# Check health endpoint manually
curl -f http://localhost:8080/health
Enable debug logging:
export LOG_LEVEL=DEBUG
python main_hosted.py
Check application logs:
# View recent logs
tail -f logs/bot.log
# Check specific date
grep "2024-01-15" logs/bot.log
- Never commit secrets: Use environment variables
- Use non-root containers: Implemented in Dockerfile.prod
- Enable health checks: Monitor application status
- Regular updates: Keep dependencies updated
- Multi-stage builds: Reduce image size
- Efficient caching: Optimize Docker layers
- Resource limits: Set appropriate memory/CPU limits
- Connection pooling: Optimize database connections
- Health endpoints: Enable monitoring integration
- Logging: Comprehensive application logging
- Metrics: Track bot performance
- Alerts: Set up failure notifications
After successful automated setup:
- Deploy to your chosen hosting service
- Configure monitoring and alerts
- Set up automated backups
- Review the Hosting Service Deployment Guide
- Check the Troubleshooting Guide for common issues