Backend Application (Laravel)
Complete guide to deploying and managing the Laravel backend application with multi-container architecture.
🏗️ Overview
Section titled “🏗️ Overview”The backend is a comprehensive Laravel application deployed using a multi-container approach in Kubernetes. It provides a robust API foundation for modern SaaS applications.
Architecture Components
Section titled “Architecture Components”Backend Deployment:├── Web Container (Nginx + PHP-FPM)├── Worker Container (Queue Processing)├── Scheduler Container (Cron Jobs)└── Init Container (Database Migrations)
🚀 Deployment Components
Section titled “🚀 Deployment Components”1. Web Container (backend-web)
Section titled “1. Web Container (backend-web)”The main web server deployment consisting of two containers working together:
Nginx Container
Section titled “Nginx Container”- Purpose: Web server and reverse proxy
- Image:
ghcr.io/hsm00/myproject-mono/backend-nginx:latest
- Port: 80 (HTTP traffic)
- Features:
- Static file serving
- PHP-FPM proxy
- Gzip compression
- Security headers
Resource Allocation:
nginx: requests: cpu: 100m memory: 128Mi limits: cpu: 500m memory: 256Mi
PHP-FPM Container
Section titled “PHP-FPM Container”- Purpose: Laravel application processing
- Image:
ghcr.io/hsm00/myproject-mono/backend-php:latest
- Port: 9000 (FastCGI)
- Features:
- Laravel 10+ application
- PHP 8.2+ runtime
- Composer dependencies
- Laravel optimizations
Resource Allocation:
php-fpm: requests: cpu: 750m memory: 1Gi limits: cpu: 1000m memory: 2Gi
Init Container (Migrations)
Section titled “Init Container (Migrations)”- Purpose: Database schema migrations
- Execution: Runs before main containers start
- Command:
php artisan migrate --force
- Ensures: Database is up-to-date before application starts
2. Worker Container (backend-worker)
Section titled “2. Worker Container (backend-worker)”Dedicated container for background job processing:
Configuration:
worker: image: backend-php:latest command: [php, artisan, queue:work] args: [--memory=3000, --timeout=600] replicas: 1 resources: requests: cpu: 800m memory: 1Gi limits: cpu: 4000m memory: 3Gi
Features:
- Processes Redis queue jobs
- Handles file uploads, email sending
- Long-running background tasks
- Automatic failure retry
3. Scheduler Container (backend-scheduler)
Section titled “3. Scheduler Container (backend-scheduler)”Replaces traditional cron jobs with Kubernetes-native scheduling:
Configuration:
scheduler: image: backend-php:latest command: [php, artisan, schedule:work] replicas: 1 resources: requests: cpu: 750m memory: 1Gi limits: cpu: 1000m memory: 2Gi
Scheduled Tasks:
- Database cleanup
- Report generation
- Cache warming
- Backup operations
🔧 Configuration
Section titled “🔧 Configuration”Environment Variables
Section titled “Environment Variables”The backend uses a comprehensive set of environment variables managed through Kubernetes ConfigMaps:
Application Settings
Section titled “Application Settings”APP_NAME=myprojectAPP_ENV=productionAPP_KEY=base64:...APP_DEBUG=falseAPP_URL=https://app.myproject.com
Database Configuration
Section titled “Database Configuration”DB_CONNECTION=mysqlDB_HOST=mariadb-serviceDB_PORT=3306DB_DATABASE=myprojectDB_USERNAME=rootDB_PASSWORD=[from secret]
Cache & Queue
Section titled “Cache & Queue”CACHE_STORE=redisQUEUE_CONNECTION=redisSESSION_DRIVER=redisREDIS_HOST=redis-serviceREDIS_PORT=6379
Email Settings
Section titled “Email Settings”MAIL_MAILER=smtpMAIL_HOST=email-smtp.eu-west-1.amazonaws.comMAIL_PORT=587MAIL_USERNAME=[from terraform output]MAIL_PASSWORD=[from terraform output]MAIL_ENCRYPTION=tls
Storage Configuration
Section titled “Storage Configuration”FILESYSTEM_DISK=r2CLOUDFLARE_R2_ACCESS_KEY_ID=[your-key]CLOUDFLARE_R2_SECRET_ACCESS_KEY=[your-secret]CLOUDFLARE_R2_BUCKET=myproject-storageCLOUDFLARE_R2_ENDPOINT=https://[account].r2.cloudflarestorage.com
Health Checks
Section titled “Health Checks”Liveness Probe
Section titled “Liveness Probe”livenessProbe: httpGet: path: /health_check port: 80 initialDelaySeconds: 30 periodSeconds: 10
Readiness Probe
Section titled “Readiness Probe”readinessProbe: httpGet: path: /health_check port: 80 initialDelaySeconds: 5 periodSeconds: 5
Health Check Endpoint
Section titled “Health Check Endpoint”The application includes a comprehensive health check endpoint at /health_check
:
// Returns JSON with system status{ "status": "healthy", "timestamp": "2024-01-10T10:00:00Z", "services": { "database": "connected", "redis": "connected", "storage": "accessible" }, "version": "1.0.0"}
🔄 Auto-scaling
Section titled “🔄 Auto-scaling”Horizontal Pod Autoscaler (HPA)
Section titled “Horizontal Pod Autoscaler (HPA)”autoscaling: enabled: true minReplicas: 1 maxReplicas: 3 targetCPUUtilizationPercentage: 70 targetMemoryUtilizationPercentage: 80
Scaling Behavior:
- Scale Up: When CPU > 70% or Memory > 80% for 2 minutes
- Scale Down: When CPU < 50% and Memory < 60% for 5 minutes
- Maximum Replicas: 3 (configurable)
Custom Metrics Scaling
Section titled “Custom Metrics Scaling”For advanced scaling based on application metrics:
# Example: Scale based on queue length- type: External external: metric: name: redis_queue_length target: type: AverageValue averageValue: "10"
🌐 Ingress Configuration
Section titled “🌐 Ingress Configuration”Domain Setup
Section titled “Domain Setup”- Primary Domain:
app.myproject.com
- SSL/TLS: Automatic Let’s Encrypt certificates
- Ingress Class: Traefik
Ingress Configuration
Section titled “Ingress Configuration”ingress: enabled: true className: traefik annotations: kubernetes.io/ingress.class: traefik cert-manager.io/cluster-issuer: letsencrypt hosts: - host: app.myproject.com paths: - path: / pathType: Prefix tls: - secretName: app-tls hosts: - app.myproject.com
🔌 WebSocket Support
Section titled “🔌 WebSocket Support”Laravel Reverb Configuration
Section titled “Laravel Reverb Configuration”The backend includes WebSocket support via Laravel Reverb:
BROADCAST_CONNECTION=reverbREVERB_APP_ID=935239REVERB_APP_KEY=[your-key]REVERB_APP_SECRET=[your-secret]REVERB_HOST=app.myproject.comREVERB_PORT=443REVERB_SCHEME=https
Service Configuration
Section titled “Service Configuration”service: ports: - port: 80 name: http - port: 6001 name: websocket
📦 Features & Integrations
Section titled “📦 Features & Integrations”Payment Processing
Section titled “Payment Processing”- Stripe Integration: Complete payment flow
- Webhook Handling: Automated payment confirmation
- Subscription Management: Recurring billing support
Email System
Section titled “Email System”- AWS SES: Transactional emails
- Templates: Branded email templates
- Notifications: Laravel notification system
File Management
Section titled “File Management”- S3-Compatible Storage: Cloudflare R2 or MinIO
- Image Processing: Automatic resizing and optimization
- CDN Distribution: Global asset delivery
Authentication
Section titled “Authentication”- Laravel Sanctum: API token authentication
- Session Management: Redis-backed sessions
- CORS Configuration: Cross-origin resource sharing
API Features
Section titled “API Features”- RESTful Endpoints: Standard HTTP methods
- Rate Limiting: Request throttling
- API Documentation: Automated API docs
- Versioning: API version management
🚀 Deployment
Section titled “🚀 Deployment”Deploy Backend Application
Section titled “Deploy Backend Application”# Basic deploymenthelm upgrade --install backend ./backend \ --namespace production \ --create-namespace
# Deploy specific versionhelm upgrade --install backend ./backend \ --namespace production \ --set image.tag=v1.2.3
# Deploy with custom valueshelm upgrade --install backend ./backend \ --namespace production \ --values custom-values.yaml
Update Application
Section titled “Update Application”# Rolling updatehelm upgrade backend ./backend \ --namespace production \ --set image.tag=v1.2.4 \ --wait --timeout=10m
# Force restart all podskubectl rollout restart deployment/backend-web -n productionkubectl rollout restart deployment/backend-worker -n productionkubectl rollout restart deployment/backend-scheduler -n production
Verify Deployment
Section titled “Verify Deployment”# Check pod statuskubectl get pods -n production -l app.kubernetes.io/name=app
# Check deployment statuskubectl rollout status deployment/backend-web -n production
# Test health endpointcurl https://app.myproject.com/health_check
📊 Monitoring
Section titled “📊 Monitoring”Application Logs
Section titled “Application Logs”# Web container logskubectl logs -f deployment/backend-web -c nginx -n productionkubectl logs -f deployment/backend-web -c php -n production
# Worker logskubectl logs -f deployment/backend-worker -n production
# Scheduler logskubectl logs -f deployment/backend-scheduler -n production
Performance Metrics
Section titled “Performance Metrics”Key metrics to monitor:
- Response Time: API endpoint performance
- Error Rate: Failed requests percentage
- Queue Length: Background job backlog
- Database Connections: Connection pool usage
- Memory Usage: PHP-FPM memory consumption
Health Monitoring
Section titled “Health Monitoring”# Application healthcurl https://app.myproject.com/health_check
# Pod healthkubectl get pods -n productionkubectl describe pod backend-web-xxx -n production
🚨 Troubleshooting
Section titled “🚨 Troubleshooting”Common Issues
Section titled “Common Issues”1. Pod Startup Issues
Section titled “1. Pod Startup Issues”# Check pod eventskubectl describe pod backend-web-xxx -n production
# Check container logskubectl logs backend-web-xxx -c php -n productionkubectl logs backend-web-xxx -c nginx -n production
2. Database Connection Issues
Section titled “2. Database Connection Issues”# Test database connectivitykubectl exec -it deployment/backend-web -c php -n production -- \ php artisan tinker --execute="DB::connection()->getPdo();"
# Check configurationkubectl get configmap backend-config -o yaml -n production
3. Performance Issues
Section titled “3. Performance Issues”# Check resource usagekubectl top pods -n production
# Check HPA statuskubectl get hpa -n productionkubectl describe hpa backend -n production
4. Queue Processing Issues
Section titled “4. Queue Processing Issues”# Check worker statuskubectl logs -f deployment/backend-worker -n production
# Check Redis queuekubectl exec -it redis-0 -- redis-cli llen queues:default
Debug Commands
Section titled “Debug Commands”# Interactive shell in PHP containerkubectl exec -it deployment/backend-web -c php -n production -- bash
# Run artisan commandskubectl exec -it deployment/backend-web -c php -n production -- \ php artisan cache:clear
# Check Laravel configurationkubectl exec -it deployment/backend-web -c php -n production -- \ php artisan config:show
🔒 Security
Section titled “🔒 Security”Container Security
Section titled “Container Security”- Non-root User: PHP-FPM runs as user ID 82
- Read-only Filesystem: Where possible
- Security Context: Restricted privileges
Application Security
Section titled “Application Security”- Input Validation: Laravel validation rules
- CSRF Protection: Built-in CSRF tokens
- SQL Injection: Eloquent ORM protection
- XSS Protection: Automatic output escaping
Network Security
Section titled “Network Security”- Internal Communication: Pod-to-pod encryption
- External Traffic: HTTPS only
- Database Access: Restricted to application pods
📝 Configuration Examples
Section titled “📝 Configuration Examples”Custom Values File
Section titled “Custom Values File”image: tag: "v1.2.3"
autoscaling: enabled: true minReplicas: 2 maxReplicas: 5
resources: requests: cpu: 1000m memory: 2Gi limits: cpu: 2000m memory: 4Gi
ingress: hosts: - host: api.yourdomain.com
Environment-Specific Configuration
Section titled “Environment-Specific Configuration”# Production deploymenthelm upgrade --install backend-prod ./backend \ --namespace production \ --values values-production.yaml
# Staging deploymenthelm upgrade --install backend-staging ./backend \ --namespace staging \ --values values-staging.yaml
🔄 Maintenance
Section titled “🔄 Maintenance”Regular Tasks
Section titled “Regular Tasks”- Monitor application logs
- Check health endpoints
- Review error rates
Weekly
Section titled “Weekly”- Update container images
- Review resource usage
- Check backup integrity
Monthly
Section titled “Monthly”- Security updates
- Performance optimization
- Capacity planning
Backup & Recovery
Section titled “Backup & Recovery”# Database backup (handled by MariaDB module)task backup DB_NAME=backend
# Configuration backupkubectl get configmap backend-config -o yaml > backup-config.yaml
# Restore procedurestask restore DB_NAME=backend BACKUP_FILE=latestkubectl apply -f backup-config.yaml
🔗 Related Documentation
Section titled “🔗 Related Documentation”- Frontend Application - Next.js deployment
- Configuration Guide - Environment setup
- Database Module - MariaDB configuration
- Monitoring - Observability setup
The Laravel backend provides a robust, scalable foundation for modern SaaS applications with enterprise-grade features and security.