Zum Inhalt springen

Backend Application (Laravel)

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

Complete guide to deploying and managing the Laravel backend application with multi-container architecture.

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.

Backend Deployment:
├── Web Container (Nginx + PHP-FPM)
├── Worker Container (Queue Processing)
├── Scheduler Container (Cron Jobs)
└── Init Container (Database Migrations)

The main web server deployment consisting of two containers working together:

  • 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
  • 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
  • Purpose: Database schema migrations
  • Execution: Runs before main containers start
  • Command: php artisan migrate --force
  • Ensures: Database is up-to-date before application starts

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

The backend uses a comprehensive set of environment variables managed through Kubernetes ConfigMaps:

APP_NAME=myproject
APP_ENV=production
APP_KEY=base64:...
APP_DEBUG=false
APP_URL=https://app.myproject.com
DB_CONNECTION=mysql
DB_HOST=mariadb-service
DB_PORT=3306
DB_DATABASE=myproject
DB_USERNAME=root
DB_PASSWORD=[from secret]
CACHE_STORE=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
REDIS_HOST=redis-service
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=email-smtp.eu-west-1.amazonaws.com
MAIL_PORT=587
MAIL_USERNAME=[from terraform output]
MAIL_PASSWORD=[from terraform output]
MAIL_ENCRYPTION=tls
FILESYSTEM_DISK=r2
CLOUDFLARE_R2_ACCESS_KEY_ID=[your-key]
CLOUDFLARE_R2_SECRET_ACCESS_KEY=[your-secret]
CLOUDFLARE_R2_BUCKET=myproject-storage
CLOUDFLARE_R2_ENDPOINT=https://[account].r2.cloudflarestorage.com
livenessProbe:
httpGet:
path: /health_check
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health_check
port: 80
initialDelaySeconds: 5
periodSeconds: 5

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"
}
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)

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"
  • Primary Domain: app.myproject.com
  • SSL/TLS: Automatic Let’s Encrypt certificates
  • Ingress Class: Traefik
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

The backend includes WebSocket support via Laravel Reverb:

BROADCAST_CONNECTION=reverb
REVERB_APP_ID=935239
REVERB_APP_KEY=[your-key]
REVERB_APP_SECRET=[your-secret]
REVERB_HOST=app.myproject.com
REVERB_PORT=443
REVERB_SCHEME=https
service:
ports:
- port: 80
name: http
- port: 6001
name: websocket
  • Stripe Integration: Complete payment flow
  • Webhook Handling: Automated payment confirmation
  • Subscription Management: Recurring billing support
  • AWS SES: Transactional emails
  • Templates: Branded email templates
  • Notifications: Laravel notification system
  • S3-Compatible Storage: Cloudflare R2 or MinIO
  • Image Processing: Automatic resizing and optimization
  • CDN Distribution: Global asset delivery
  • Laravel Sanctum: API token authentication
  • Session Management: Redis-backed sessions
  • CORS Configuration: Cross-origin resource sharing
  • RESTful Endpoints: Standard HTTP methods
  • Rate Limiting: Request throttling
  • API Documentation: Automated API docs
  • Versioning: API version management
Terminal window
# Basic deployment
helm upgrade --install backend ./backend \
--namespace production \
--create-namespace
# Deploy specific version
helm upgrade --install backend ./backend \
--namespace production \
--set image.tag=v1.2.3
# Deploy with custom values
helm upgrade --install backend ./backend \
--namespace production \
--values custom-values.yaml
Terminal window
# Rolling update
helm upgrade backend ./backend \
--namespace production \
--set image.tag=v1.2.4 \
--wait --timeout=10m
# Force restart all pods
kubectl rollout restart deployment/backend-web -n production
kubectl rollout restart deployment/backend-worker -n production
kubectl rollout restart deployment/backend-scheduler -n production
Terminal window
# Check pod status
kubectl get pods -n production -l app.kubernetes.io/name=app
# Check deployment status
kubectl rollout status deployment/backend-web -n production
# Test health endpoint
curl https://app.myproject.com/health_check
Terminal window
# Web container logs
kubectl logs -f deployment/backend-web -c nginx -n production
kubectl logs -f deployment/backend-web -c php -n production
# Worker logs
kubectl logs -f deployment/backend-worker -n production
# Scheduler logs
kubectl logs -f deployment/backend-scheduler -n production

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
Terminal window
# Application health
curl https://app.myproject.com/health_check
# Pod health
kubectl get pods -n production
kubectl describe pod backend-web-xxx -n production
Terminal window
# Check pod events
kubectl describe pod backend-web-xxx -n production
# Check container logs
kubectl logs backend-web-xxx -c php -n production
kubectl logs backend-web-xxx -c nginx -n production
Terminal window
# Test database connectivity
kubectl exec -it deployment/backend-web -c php -n production -- \
php artisan tinker --execute="DB::connection()->getPdo();"
# Check configuration
kubectl get configmap backend-config -o yaml -n production
Terminal window
# Check resource usage
kubectl top pods -n production
# Check HPA status
kubectl get hpa -n production
kubectl describe hpa backend -n production
Terminal window
# Check worker status
kubectl logs -f deployment/backend-worker -n production
# Check Redis queue
kubectl exec -it redis-0 -- redis-cli llen queues:default
Terminal window
# Interactive shell in PHP container
kubectl exec -it deployment/backend-web -c php -n production -- bash
# Run artisan commands
kubectl exec -it deployment/backend-web -c php -n production -- \
php artisan cache:clear
# Check Laravel configuration
kubectl exec -it deployment/backend-web -c php -n production -- \
php artisan config:show
  • Non-root User: PHP-FPM runs as user ID 82
  • Read-only Filesystem: Where possible
  • Security Context: Restricted privileges
  • Input Validation: Laravel validation rules
  • CSRF Protection: Built-in CSRF tokens
  • SQL Injection: Eloquent ORM protection
  • XSS Protection: Automatic output escaping
  • Internal Communication: Pod-to-pod encryption
  • External Traffic: HTTPS only
  • Database Access: Restricted to application pods
custom-values.yaml
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
Terminal window
# Production deployment
helm upgrade --install backend-prod ./backend \
--namespace production \
--values values-production.yaml
# Staging deployment
helm upgrade --install backend-staging ./backend \
--namespace staging \
--values values-staging.yaml
  • Monitor application logs
  • Check health endpoints
  • Review error rates
  • Update container images
  • Review resource usage
  • Check backup integrity
  • Security updates
  • Performance optimization
  • Capacity planning
Terminal window
# Database backup (handled by MariaDB module)
task backup DB_NAME=backend
# Configuration backup
kubectl get configmap backend-config -o yaml > backup-config.yaml
# Restore procedures
task restore DB_NAME=backend BACKUP_FILE=latest
kubectl apply -f backup-config.yaml

The Laravel backend provides a robust, scalable foundation for modern SaaS applications with enterprise-grade features and security.