# 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. ## Table of Contents 1. [Overview](#overview) 2. [Prerequisites](#prerequisites) 3. [Automated Setup Script](#automated-setup-script) 4. [Production Docker Configuration](#production-docker-configuration) 5. [Environment Variables](#environment-variables) 6. [Health Check Integration](#health-check-integration) 7. [Non-Interactive Deployment](#non-interactive-deployment) 8. [Verification and Testing](#verification-and-testing) 9. [Troubleshooting](#troubleshooting) ## Overview 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 ## Prerequisites 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) ## Automated Setup Script The `docker-setup.sh` script handles the complete setup process: ### Running the Setup ```bash # Make the script executable chmod +x docker-setup.sh # Run the automated setup ./docker-setup.sh ``` ### What the Script Does 1. **Environment Validation**: Checks for required environment variables 2. **Automatic Generation**: Creates missing variables like `SECRET_KEY` 3. **Directory Setup**: Creates necessary directories (`logs/`, `data/`) 4. **Database Initialization**: Sets up SQLite database structure 5. **Docker Image Build**: Creates production-ready Docker image 6. **Verification**: Runs deployment readiness checks ### Script Features - **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 ## Production Docker Configuration ### Dockerfile.prod The production Dockerfile uses a multi-stage build process: ```dockerfile # 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"] ``` ### Key Features - **Multi-Stage Build**: Reduces final image size - **Non-Root User**: Enhanced security - **Health Checks**: Built-in monitoring - **Environment Flexibility**: Dynamic port configuration ## Environment Variables ### Required Variables ```bash # 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 ``` ### Optional Variables ```bash # 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 ``` ### Auto-Generation The setup script automatically generates: - `SECRET_KEY`: 32-character cryptographically secure key - `DATABASE_URL`: SQLite database path - `PORT`: Default port configuration ## Health Check Integration ### Health Check Endpoints The bot includes a web server with health check endpoints: - **`/health`**: Basic health status - **`/ready`**: Readiness probe for containers - **`/`**: Simple status page ### Health Check Implementation ```python 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) ``` ### Hosting Service Integration - **Render**: Uses `/health` for health checks - **Railway**: Monitors `/ready` endpoint - **Heroku**: Checks `/` for basic connectivity ## Non-Interactive Deployment ### Automated Environment Detection The system automatically detects hosting environments: ```python 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' ``` ### Platform-Specific Configurations Each hosting service has optimized configurations: #### Render Configuration (render.yaml) ```yaml services: - type: web name: utils-bot-plus env: docker dockerfilePath: ./Dockerfile.prod healthCheckPath: /health envVars: - key: DISCORD_TOKEN sync: false - key: PORT value: 10000 ``` #### Railway Configuration (railway.json) ```json { "build": { "builder": "dockerfile", "dockerfilePath": "Dockerfile.prod" }, "deploy": { "healthcheckPath": "/ready", "healthcheckTimeout": 30 } } ``` #### Heroku Configuration (Procfile) ``` web: python main_hosted.py ``` ## Verification and Testing ### Deployment Verification Script The `verify_deployment.py` script checks deployment readiness: ```bash python verify_deployment.py ``` ### Verification Checks 1. **Environment Variables**: Validates all required variables 2. **File Structure**: Ensures all necessary files exist 3. **Database Connection**: Tests database connectivity 4. **Bot Initialization**: Verifies bot can start 5. **Health Endpoints**: Tests web server functionality ### Test Results The script provides detailed results: ``` ✅ Environment Variables: OK ✅ File Structure: OK ✅ Database Connection: OK ✅ Bot Initialization: OK ✅ Health Endpoints: OK 🚀 Deployment Ready! ``` ## Troubleshooting ### Common Issues #### 1. Permission Errors ```bash # Fix file permissions chmod +x docker-setup.sh sudo chown -R $USER:$USER . ``` #### 2. Docker Build Failures ```bash # Clean Docker cache docker system prune -f docker build --no-cache -f Dockerfile.prod -t utils-bot-plus . ``` #### 3. Environment Variable Issues ```bash # Regenerate environment file rm .env ./docker-setup.sh ``` #### 4. Health Check Failures ```bash # Check health endpoint manually curl -f http://localhost:8080/health ``` ### Debug Mode Enable debug logging: ```bash export LOG_LEVEL=DEBUG python main_hosted.py ``` ### Log Analysis Check application logs: ```bash # View recent logs tail -f logs/bot.log # Check specific date grep "2024-01-15" logs/bot.log ``` ## Best Practices ### Security 1. **Never commit secrets**: Use environment variables 2. **Use non-root containers**: Implemented in Dockerfile.prod 3. **Enable health checks**: Monitor application status 4. **Regular updates**: Keep dependencies updated ### Performance 1. **Multi-stage builds**: Reduce image size 2. **Efficient caching**: Optimize Docker layers 3. **Resource limits**: Set appropriate memory/CPU limits 4. **Connection pooling**: Optimize database connections ### Monitoring 1. **Health endpoints**: Enable monitoring integration 2. **Logging**: Comprehensive application logging 3. **Metrics**: Track bot performance 4. **Alerts**: Set up failure notifications ## Next Steps After successful automated setup: 1. Deploy to your chosen hosting service 2. Configure monitoring and alerts 3. Set up automated backups 4. Review the [Hosting Service Deployment Guide](17.%20Hosting-Service-Deployment-Guide.md) 5. Check the [Troubleshooting Guide](12.%20Troubleshooting.md) for common issues ## Related Documentation - [Hosting Service Deployment Guide](17.%20Hosting-Service-Deployment-Guide.md) - [Configuration Guide](05.%20Configuration-Guide.md) - [Deployment Guide](06.%20Deployment-Guide.md) - [Security Guide](11.%20Security-Guide.md) - [Troubleshooting](12.%20Troubleshooting.md)