Docker Deployment

Comprehensive Docker support for Khadem applications with automated deployment, multi-service orchestration, and production-ready configurations.

Automated Docker Setup

Khadem provides automated Docker setup through the build command, generating production-ready Dockerfiles and docker-compose configurations.

bash
# Generate complete Docker setup
dart run khadem build --docker

# Or specify services
dart run khadem build --docker --services=mysql,redis,nginx

# Generate for production
dart run khadem build --docker --env=production

Automated Features

  • Multi-stage Dockerfile generation
  • Docker Compose with multiple database options
  • Environment configuration templates
  • Nginx reverse proxy configuration
  • SSL/TLS setup templates
  • Health checks and monitoring

Generated Dockerfile

Khadem automatically generates optimized Dockerfiles with multi-stage builds, security hardening, and production optimizations.

dockerfile
# Auto-generated multi-stage Dockerfile
FROM dart:3.0-sdk AS build

WORKDIR /app
COPY pubspec.* ./
RUN dart pub get

COPY . .
RUN dart pub get --offline
RUN dart compile exe bin/server.dart -o bin/server

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=build /app/bin/server /app/bin/server
COPY --from=build /app/config /app/config
COPY --from=build /app/public /app/public

RUN useradd --user-group --create-home --shell /bin/bash app
RUN chown -R app:app /app
USER app

EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1

CMD ["/app/bin/server"]

Production Optimizations

  • AOT compilation for faster startup and lower memory usage
  • Non-root user execution for security
  • Minimal runtime image (Debian slim)
  • Health checks for container monitoring
  • Proper signal handling and graceful shutdown
  • Multi-stage build for smaller final images

Multi-Service Docker Compose

Khadem generates comprehensive docker-compose configurations with support for multiple databases, caching, and reverse proxy services.

yaml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - APP_ENV=production
      - DB_CONNECTION=mysql
      - DB_HOST=mysql
      - DB_PORT=3306
      - DB_DATABASE=khadem
      - DB_USERNAME=khadem
      - DB_PASSWORD=secret
      - REDIS_HOST=redis
      - REDIS_PORT=6379
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_healthy
    volumes:
      - ./storage:/app/storage
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped

  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: khadem
      MYSQL_USER: khadem
      MYSQL_PASSWORD: secret
    volumes:
      - mysql_data:/var/lib/mysql
      - ./docker/mysql/my.cnf:/etc/mysql/conf.d/my.cnf
    ports:
      - "3306:3306"
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data
    ports:
      - "6379:6379"
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./docker/nginx/ssl:/etc/nginx/ssl
      - ./storage/app/public:/var/www/html
    depends_on:
      - app
    restart: unless-stopped

volumes:
  mysql_data:
  redis_data:

Supported Services

  • MySQL: MySQL 8.0 with custom configuration
  • PostgreSQL: PostgreSQL 15 with optimized settings
  • MongoDB: MongoDB 7 with authentication
  • Redis: Redis 7 with persistence
  • Nginx: Reverse proxy with SSL support

Service Configuration

  • Automatic environment variable mapping
  • Proper service dependencies
  • Persistent data volumes
  • Health checks and restart policies
  • Network isolation and security

Development Environment

Streamlined development setup with hot reload, debugging, and service orchestration for Khadem applications.

yaml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "3000:3000"
      - "8181:8181"  # Dart VM service for debugging
    volumes:
      - .:/app
      - /app/.dart_tool
    environment:
      - APP_ENV=development
      - DART_VM_OPTIONS=--enable-vm-service=8181/0.0.0.0:8181
    command: dart run --enable-vm-service bin/server.dart
    depends_on:
      - mysql
      - redis

  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: khadem_dev
      MYSQL_USER: khadem
      MYSQL_PASSWORD: secret
    volumes:
      - mysql_dev_data:/var/lib/mysql
    ports:
      - "3306:3306"

  redis:
    image: redis:7-alpine
    volumes:
      - redis_dev_data:/data
    ports:
      - "6379:6379"

volumes:
  mysql_dev_data:
  redis_dev_data:

Development Features

  • Hot Reload: Automatic code reloading during development
  • VM Service: Integrated debugging with Dart DevTools
  • Volume Mounting: Live code synchronization
  • Service Isolation: Separate databases for development
  • Port Mapping: Easy access to all services

Environment Configuration

Khadem automatically generates comprehensive environment configuration files for different deployment scenarios.

bash
# Production Environment Configuration
APP_NAME=KhademApp
APP_ENV=production
APP_KEY=base64:your_app_key_here
APP_DEBUG=false
APP_URL=https://yourdomain.com

# Database Configuration
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=khadem
DB_USERNAME=khadem
DB_PASSWORD=your_secure_password

# Redis Configuration
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

# Cache Configuration
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

# Mail Configuration
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@yourdomain.com"
MAIL_FROM_NAME="${APP_NAME}"

# Storage Configuration
FILESYSTEM_DISK=local
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

# Logging
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=error

Database Configuration

  • MySQL: Full MySQL 8.0 support
  • PostgreSQL: PostgreSQL with advanced features
  • MongoDB: NoSQL database integration
  • SQLite: File-based database for development

Service Integration

  • Redis: Caching and session storage
  • Queue: Background job processing
  • Mail: Email service configuration
  • Storage: File storage drivers

Nginx Reverse Proxy

Khadem automatically generates optimized Nginx configurations for production deployments with SSL, caching, and security headers.

nginx
events {
    worker_connections 1024;
}

http {
    upstream khadem_app {
        server app:3000;
    }

    server {
        listen 80;
        server_name yourdomain.com;

        # Security headers
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        # Gzip compression
        gzip on;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            proxy_pass http://khadem_app;
            proxy_set_header Host $host;
            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;

            # Timeout settings
            proxy_connect_timeout 30s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
        }

        # Static files caching
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }

        # API rate limiting
        location /api/ {
            limit_req zone=api burst=10 nodelay;
            proxy_pass http://khadem_app;
        }
    }
}

# Rate limiting zones
limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;
limit_req_status 429;

Nginx Features

  • Load Balancing: Distribute traffic across multiple app instances
  • SSL Termination: Handle HTTPS encryption at the proxy level
  • Static File Serving: Serve assets directly from Nginx for better performance
  • Rate Limiting: Protect against abuse and DDoS attacks
  • Security Headers: Automatic security header injection
  • Gzip Compression: Compress responses for faster delivery

Khadem Docker Commands

Use Khadem's CLI to manage Docker deployments with automated configuration and deployment workflows.

bash
# Generate Docker setup
dart run khadem build --docker

# Build and start services
docker-compose up -d

# View logs
docker-compose logs -f app

# Run migrations in container
docker-compose exec app dart run khadem migrate

# Run seeders
docker-compose exec app dart run khadem db:seed

# Stop all services
docker-compose down

# Rebuild specific service
docker-compose up -d --build app

# Scale services
docker-compose up -d --scale app=3

CLI Docker Integration

  • Automated Setup: khadem build --docker generates everything
  • Service Selection: Choose specific services to include
  • Environment Generation: Auto-configured environment files
  • Production Ready: Optimized for performance and security
  • Multi-Platform: Cross-platform deployment support

Production Deployment

Streamlined production deployment with automated Docker generation, health checks, and zero-downtime updates.

bash
#!/bin/bash
# Automated Production Deployment Script

set -e

echo "๐Ÿš€ Starting Khadem production deployment..."

# Pull latest changes
git pull origin main

# Generate Docker setup if needed
if [ ! -f "docker-compose.yml" ]; then
    echo "๐Ÿ“ฆ Generating Docker configuration..."
    dart run khadem build --docker --env=production
fi

# Build and deploy
echo "๐Ÿ—๏ธ  Building and deploying services..."
docker-compose up -d --build

# Wait for services to be ready
echo "โณ Waiting for services to start..."
sleep 30

# Run database migrations
echo "๐Ÿ—„๏ธ  Running database migrations..."
docker-compose exec -T app dart run khadem migrate

# Run health checks
echo "๐Ÿฅ Running health checks..."
if curl -f http://localhost:3000/health; then
    echo "โœ… Application health check passed!"
else
    echo "โŒ Application health check failed!"
    exit 1
fi

# Verify database connection
docker-compose exec -T app dart run khadem db:check || {
    echo "โŒ Database connection failed!"
    exit 1
}

# Clean up old images
echo "๐Ÿงน Cleaning up old Docker images..."
docker image prune -f

echo "๐ŸŽ‰ Production deployment completed successfully!"
echo "๐ŸŒ Application is running at: http://your-server-ip:3000"

Production Best Practices

  • Blue-Green Deployment: Zero-downtime updates with service switching
  • Health Checks: Automated monitoring and recovery
  • Resource Limits: Memory and CPU constraints
  • Security Scanning: Container vulnerability assessment
  • Backup Strategy: Automated database and file backups
  • Monitoring Integration: Logs, metrics, and alerting

SSL/TLS Configuration

Secure your Khadem application with automated SSL/TLS configuration and Let's Encrypt integration.

nginx
server {
    listen 443 ssl http2;
    server_name yourdomain.com;

    # SSL configuration
    ssl_certificate /etc/ssl/certs/yourdomain.crt;
    ssl_certificate_key /etc/ssl/private/yourdomain.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # Security headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    location / {
        proxy_pass http://khadem_app;
        proxy_set_header Host $host;
        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;
    }
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$server_name$request_uri;
}

SSL Best Practices

  • Let's Encrypt: Automated SSL certificate generation
  • HSTS Headers: Force HTTPS connections
  • Modern Ciphers: TLS 1.2+ with secure cipher suites
  • Certificate Renewal: Automatic renewal before expiration
  • HTTP Redirect: Automatic HTTP to HTTPS redirection

Monitoring and Logging

Comprehensive monitoring and logging setup with Prometheus, Grafana, and structured logging for Khadem applications.

yaml
version: '3.8'

services:
  app:
    # ... existing app config
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
    deploy:
      resources:
        limits:
          memory: 512M
        reservations:
          memory: 256M

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--web.console.libraries=/etc/prometheus/console_libraries'
      - '--web.console.templates=/etc/prometheus/consoles'
    restart: unless-stopped

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3001:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
      - GF_USERS_ALLOW_SIGN_UP=false
    volumes:
      - grafana_data:/var/lib/grafana
      - ./monitoring/grafana/provisioning:/etc/grafana/provisioning
    depends_on:
      - prometheus
    restart: unless-stopped

  cadvisor:
    image: gcr.io/cadvisor/cadvisor:latest
    ports:
      - "8080:8080"
    volumes:
      - /:/rootfs:ro
      - /var/run:/var/run:ro
      - /sys:/sys:ro
      - /var/lib/docker/:/var/lib/docker:ro
      - /dev/disk/:/dev/disk:ro
    devices:
      - /dev/kmsg
    restart: unless-stopped

  node-exporter:
    image: prom/node-exporter:latest
    ports:
      - "9100:9100"
    volumes:
      - /proc:/host/proc:ro
      - /sys:/host/sys:ro
      - /:/rootfs:ro
    command:
      - '--path.procfs=/host/proc'
      - '--path.rootfs=/rootfs'
      - '--path.sysfs=/host/sys'
      - '--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)'
    restart: unless-stopped

volumes:
  prometheus_data:
  grafana_data:

Monitoring Stack

  • Prometheus: Metrics collection and alerting
  • Grafana: Dashboard visualization
  • cAdvisor: Container resource monitoring
  • Node Exporter: System metrics

Logging Features

  • Structured Logging: JSON format with context
  • Log Rotation: Automatic log file management
  • Centralized Logging: ELK stack integration
  • Error Tracking: Sentry integration

Best Practices and Troubleshooting

Essential best practices and common troubleshooting scenarios for Docker deployments with Khadem.

Docker Best Practices

  • Multi-stage Builds: Reduce image size and attack surface
  • Non-root User: Run containers as non-privileged user
  • Environment Variables: Use env vars for configuration
  • Health Checks: Implement proper health monitoring
  • Resource Limits: Set memory and CPU constraints
  • Security Scanning: Scan images for vulnerabilities
  • Version Pinning: Pin base image versions
  • Minimal Images: Use slim/alpine base images

Troubleshooting

  • Container Won't Start: Check logs with docker-compose logs
  • Port Conflicts: Verify ports aren't already in use
  • Database Connection: Check service dependencies and health
  • Memory Issues: Monitor container resource usage
  • Permission Errors: Ensure proper file permissions
  • Network Issues: Verify Docker network configuration

Common Commands

bash
# View all running containers
docker-compose ps

# View logs for specific service
docker-compose logs app
docker-compose logs -f mysql

# Check container resource usage
docker stats

# Inspect container configuration
docker inspect khadem_app_1

# Execute commands in running container
docker-compose exec app bash
docker-compose exec mysql mysql -u khadem -p khadem

# Check service health
docker-compose exec app curl -f http://localhost:3000/health

# Restart specific service
docker-compose restart app

# Rebuild and restart service
docker-compose up -d --build app

# Clean up unused resources
docker system prune -a
docker volume prune

# View Docker networks
docker network ls
docker network inspect khadem_default

On this page