Deployment Guide
Overview
Section titled “Overview”This guide provides detailed instructions for deploying CreativeDynamics in production environments. The library supports various deployment scenarios, from single-server installations to distributed cloud deployments.
Prerequisites
Section titled “Prerequisites”System Requirements
Section titled “System Requirements”- Operating System: Linux (Ubuntu 20.04+ recommended), macOS, or Windows Server 2019+
- Python: 3.10 or higher
- Memory: Minimum 4GB RAM, 8GB+ recommended for production workloads
- Storage: 10GB+ depending on data volume
- CPU: 2+ cores recommended for concurrent processing
Software Dependencies
Section titled “Software Dependencies”# Core dependenciespython >= 3.10roughpy >= 0.1.0numpy >= 1.24.0pandas >= 2.0.0fastapi >= 0.100.0uvicorn >= 0.23.0Installation Methods
Section titled “Installation Methods”1. Production Installation (Source)
Section titled “1. Production Installation (Source)”# Create virtual environmentpython -m venv creativedynamics-envsource creativedynamics-env/bin/activate # Linux/macOS# orcreativedynamics-env\Scripts\activate # Windows
# Install packagepip install .
# Verify installationpython -c "import creativedynamics; print(creativedynamics.__version__)"2. Docker Deployment
Section titled “2. Docker Deployment”Create a Dockerfile:
FROM python:3.10-slim
WORKDIR /app
# Install system dependenciesRUN apt-get update && \ apt-get install -y --no-install-recommends \ build-essential \ && rm -rf /var/lib/apt/lists/*
# Copy application and install with dependenciesCOPY . .
# Install CreativeDynamics with all dependencies from pyproject.tomlRUN pip install --no-cache-dir -e .
# Expose API portEXPOSE 5001
# Run API serverCMD ["uvicorn", "creativedynamics.api.main:app", "--host", "0.0.0.0", "--port", "5001"]Build and run:
docker build -t creativedynamics:latest .docker run -d -p 5001:5001 --name creativedynamics creativedynamics:latest3. Kubernetes Deployment
Section titled “3. Kubernetes Deployment”Create creativedynamics-deployment.yaml:
apiVersion: apps/v1kind: Deploymentmetadata: name: creativedynamicsspec: replicas: 3 selector: matchLabels: app: creativedynamics template: metadata: labels: app: creativedynamics spec: containers: - name: creativedynamics image: creativedynamics:latest ports: - containerPort: 5001 resources: requests: memory: "2Gi" cpu: "1" limits: memory: "4Gi" cpu: "2" env: - name: WORKERS value: "4"---apiVersion: v1kind: Servicemetadata: name: creativedynamics-servicespec: selector: app: creativedynamics ports: - protocol: TCP port: 80 targetPort: 5001 type: LoadBalancerDeploy:
kubectl apply -f creativedynamics-deployment.yamlAPI Server Configuration
Section titled “API Server Configuration”Production Settings
Section titled “Production Settings”Create production_config.py:
import osfrom typing import Optional
class ProductionConfig: # API Settings API_HOST: str = os.getenv("API_HOST", "0.0.0.0") API_PORT: int = int(os.getenv("API_PORT", "5001")) WORKERS: int = int(os.getenv("WORKERS", "4"))
# Security API_KEY: Optional[str] = os.getenv("API_KEY") CORS_ORIGINS: list = os.getenv("CORS_ORIGINS", "*").split(",")
# Performance MAX_UPLOAD_SIZE: int = int(os.getenv("MAX_UPLOAD_SIZE", "100")) # MB REQUEST_TIMEOUT: int = int(os.getenv("REQUEST_TIMEOUT", "300")) # seconds
# Logging LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO") LOG_FILE: str = os.getenv("LOG_FILE", "/var/log/creativedynamics/api.log")Running with Gunicorn (Production)
Section titled “Running with Gunicorn (Production)”pip install gunicorn
# Run with multiple workersgunicorn creativedynamics.api.main:app \ --workers 4 \ --worker-class uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:5001 \ --timeout 300 \ --access-logfile /var/log/creativedynamics/access.log \ --error-logfile /var/log/creativedynamics/error.logReverse Proxy Configuration
Section titled “Reverse Proxy Configuration”Nginx Configuration
Section titled “Nginx Configuration”Create /etc/nginx/sites-available/creativedynamics:
server { listen 80; server_name api.creativedynamics.example.com;
# Redirect to HTTPS return 301 https://$server_name$request_uri;}
server { listen 443 ssl http2; server_name api.creativedynamics.example.com;
# SSL certificates ssl_certificate /etc/ssl/certs/creativedynamics.crt; ssl_certificate_key /etc/ssl/private/creativedynamics.key;
# SSL configuration ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5;
# Proxy settings location / { proxy_pass http://localhost:5001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;
# Timeouts proxy_connect_timeout 300s; proxy_send_timeout 300s; proxy_read_timeout 300s; }
# API documentation location /docs { proxy_pass http://localhost:5001/docs; }
location /redoc { proxy_pass http://localhost:5001/redoc; }
# File upload limits client_max_body_size 100M;}Enable the configuration:
sudo ln -s /etc/nginx/sites-available/creativedynamics /etc/nginx/sites-enabled/sudo nginx -tsudo systemctl reload nginxSystemd Service
Section titled “Systemd Service”Create /etc/systemd/system/creativedynamics.service:
[Unit]Description=CreativeDynamics API ServerAfter=network.target
[Service]Type=execUser=creativedynamicsGroup=creativedynamicsWorkingDirectory=/opt/creativedynamicsEnvironment="PATH=/opt/creativedynamics/venv/bin"ExecStart=/opt/creativedynamics/venv/bin/gunicorn \ creativedynamics.api.main:app \ --workers 4 \ --worker-class uvicorn.workers.UvicornWorker \ --bind unix:/var/run/creativedynamics/creativedynamics.sock \ --timeout 300 \ --access-logfile /var/log/creativedynamics/access.log \ --error-logfile /var/log/creativedynamics/error.log
Restart=alwaysRestartSec=10
[Install]WantedBy=multi-user.targetEnable and start the service:
sudo systemctl daemon-reloadsudo systemctl enable creativedynamicssudo systemctl start creativedynamicssudo systemctl status creativedynamicsEnvironment Variables
Section titled “Environment Variables”Required Variables
Section titled “Required Variables”# .env file# API ConfigurationAPI_HOST=0.0.0.0API_PORT=5001WORKERS=4
# SecurityAPI_KEY=your-secure-api-key-hereCORS_ORIGINS=https://app.example.com,https://dashboard.example.com
# PerformanceMAX_UPLOAD_SIZE=100REQUEST_TIMEOUT=300
# LoggingLOG_LEVEL=INFOLOG_FILE=/var/log/creativedynamics/api.log
# Data StorageDATA_PATH=/var/lib/creativedynamics/dataOUTPUT_PATH=/var/lib/creativedynamics/outputTEMP_PATH=/tmp/creativedynamicsHealth Checks
Section titled “Health Checks”Liveness Probe
Section titled “Liveness Probe”curl -f http://localhost:5001/health || exit 1Readiness Probe
Section titled “Readiness Probe”# Add to your deployed FastAPI application if you need a separate readiness probe@app.get("/ready")async def readiness(): """Check if the service is ready to handle requests.""" try: # Check database connectivity if applicable # Check external service dependencies return {"status": "ready", "timestamp": datetime.utcnow()} except Exception as e: return JSONResponse( status_code=503, content={"status": "not ready", "error": str(e)} )Backup and Recovery
Section titled “Backup and Recovery”Data Backup
Section titled “Data Backup”#!/bin/bash# backup.sh - Run daily via cron
BACKUP_DIR="/backup/creativedynamics"DATA_DIR="/var/lib/creativedynamics"DATE=$(date +%Y%m%d_%H%M%S)
# Create backup directorymkdir -p "$BACKUP_DIR"
# Backup data and configurationtar -czf "$BACKUP_DIR/creativedynamics_${DATE}.tar.gz" \ "$DATA_DIR" \ "/etc/creativedynamics" \ "/var/log/creativedynamics"
# Keep only last 30 days of backupsfind "$BACKUP_DIR" -name "*.tar.gz" -mtime +30 -deleteRecovery Procedure
Section titled “Recovery Procedure”# Restore from backupBACKUP_FILE="/backup/creativedynamics/creativedynamics_20240101_120000.tar.gz"
# Stop servicesudo systemctl stop creativedynamics
# Extract backuptar -xzf "$BACKUP_FILE" -C /
# Start servicesudo systemctl start creativedynamicsTroubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”-
Port Already in Use
Terminal window # Find process using port 5001sudo lsof -i :5001# Kill the process if neededsudo kill -9 <PID> -
Permission Denied
Terminal window # Fix permissionssudo chown -R creativedynamics:creativedynamics /opt/creativedynamicssudo chmod -R 755 /opt/creativedynamics -
Module Import Errors
Terminal window # Reinstall dependenciespip install --upgrade --force-reinstall creativedynamics -
Memory Issues
Terminal window # Increase system limitsecho "creativedynamics soft nofile 65536" >> /etc/security/limits.confecho "creativedynamics hard nofile 65536" >> /etc/security/limits.conf
Performance Tuning
Section titled “Performance Tuning”API Server Optimisation
Section titled “API Server Optimisation”# Add to API configurationfrom fastapi import FastAPIfrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Enable compressionapp.add_middleware(GZipMiddleware, minimum_size=1000)
# Configure CORSapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)System Tuning
Section titled “System Tuning”# Increase file descriptorsulimit -n 65536
# Optimise TCP settingssudo sysctl -w net.core.somaxconn=65535sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535sudo sysctl -w net.ipv4.tcp_tw_reuse=1Security Considerations
Section titled “Security Considerations”- Use HTTPS in production
- Implement API key authentication
- Set up rate limiting
- Configure firewall rules
- Regular security updates
- Monitor access logs
- Implement request validation
- Use secure headers
Next Steps
Section titled “Next Steps”- Review Monitoring Guide for observability setup
- See Scaling Guide for horizontal scaling strategies
- Check Security Best Practices for hardening recommendations