Skip to content

16. Docker Automated Setup Guide

ad1107 edited this page May 25, 2025 · 1 revision

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
  2. Prerequisites
  3. Automated Setup Script
  4. Production Docker Configuration
  5. Environment Variables
  6. Health Check Integration
  7. Non-Interactive Deployment
  8. Verification and Testing
  9. 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

# 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:

# 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

# 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

# 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

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:

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)

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)

{
  "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:

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

# Fix file permissions
chmod +x docker-setup.sh
sudo chown -R $USER:$USER .

2. Docker Build Failures

# Clean Docker cache
docker system prune -f
docker build --no-cache -f Dockerfile.prod -t utils-bot-plus .

3. Environment Variable Issues

# Regenerate environment file
rm .env
./docker-setup.sh

4. Health Check Failures

# Check health endpoint manually
curl -f http://localhost:8080/health

Debug Mode

Enable debug logging:

export LOG_LEVEL=DEBUG
python main_hosted.py

Log Analysis

Check application logs:

# 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
  5. Check the Troubleshooting Guide for common issues

Related Documentation

Clone this wiki locally