Unlocking High Availability: Advanced Kubernetes Strategies for Laravel Applications with Integrated CI/CD and Disaster Recovery
Kubernetes Cluster Setup for Laravel HA
Achieving high availability for Laravel applications on Kubernetes necessitates a robust cluster configuration. This involves not just deploying the application but also ensuring its dependencies, such as databases and caching layers, are equally resilient. We’ll focus on a multi-node setup with proper resource allocation and network policies.
Database High Availability: PostgreSQL with Patroni
For stateful applications like Laravel, a highly available database is paramount. PostgreSQL with Patroni offers automated failover and replication. Here’s a sample Kubernetes deployment for PostgreSQL using Patroni, assuming you have a distributed consensus store like etcd or Consul configured.
First, define the Patroni configuration. This typically involves a ConfigMap.
apiVersion: v1
kind: ConfigMap
metadata:
name: postgresql-patroni-config
data:
patroni.yml: |
scope: my-laravel-db
namespace: default # Or your application's namespace
restapi:
listen: 0.0.0.0:8008
etcd: # Or your chosen consensus store
host: etcd.default.svc.cluster.local:2379
postgresql:
listen: 0.0.0.0:5432
connect_address: &connect_address '{{.Name}}.{{.Namespace}}.svc.cluster.local:5432'
data_dir: /var/lib/postgresql/data
pg_hba:
- host replication all all trust
- host all all all md5
parameters:
max_connections: 100
shared_buffers: 256MB
effective_cache_size: 768MB
maintenance_work_mem: 64MB
wal_level: replica
hot_standby: "on"
max_wal_senders: 5
max_replication_slots: 5
tags:
nofailover: "false"
noloadbalance: "false"
bootstrap:
dcs:
ttl: 30
loop_wait: 10
retry_timeout: 10
maximum_lag_on_failover: 1048576 # 1MB
postgresql:
use_pg_rewind: true
recovery_conf:
standby_mode: "on"
primary_conninfo: "host=%s user=%s password=%s hostaddr=%s port=%s"
restore_command: "cp /tmp/wal/%f %p"
recovery_target_timeline: "latest"
# ... other Patroni configurations
Next, the StatefulSet for PostgreSQL instances. This ensures stable network identities and persistent storage for each replica.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgresql
spec:
serviceName: postgresql-ha
replicas: 3 # Minimum 3 for quorum in etcd/Consul
selector:
matchLabels:
app: postgresql
template:
metadata:
labels:
app: postgresql
spec:
containers:
- name: postgresql
image: postgres:14 # Use a specific, tested version
ports:
- containerPort: 5432
name: postgresql
- containerPort: 8008
name: patroni
env:
- name: PATRONI_CONFIG_MAP
value: postgresql-patroni-config
- name: PATRONI_SCOPE
value: my-laravel-db
- name: PATRONI_REPLICA_COUNT
value: "3"
- name: PATRONI_స్వామి_USER
valueFrom:
secretKeyRef:
name: postgresql-credentials
key: user
- name: PATRONI_స్వామి_PASSWORD
valueFrom:
secretKeyRef:
name: postgresql-credentials
key: password
- name: PATRONI_స్వామి_DATABASE
value: app_db # Your Laravel DB name
volumeMounts:
- name: datadir
mountPath: /var/lib/postgresql/data
volumes:
- name: datadir
emptyDir: {} # Patroni will manage data initialization
volumeClaimTemplates:
- metadata:
name: datadir
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi # Adjust based on your needs
A Headless Service is crucial for StatefulSets to provide stable DNS entries for each pod.
apiVersion: v1
kind: Service
metadata:
name: postgresql-ha
labels:
app: postgresql
spec:
ports:
- port: 5432
targetPort: 5432
name: postgresql
- port: 8008
targetPort: 8008
name: patroni
clusterIP: None # Headless service
selector:
app: postgresql
Finally, a regular Service to act as the load balancer/proxy for your Laravel application to connect to.
apiVersion: v1
kind: Service
metadata:
name: postgresql-readwrite
labels:
app: postgresql
spec:
ports:
- port: 5432
targetPort: 5432
name: postgresql
selector:
app: postgresql
# This service will automatically point to the current primary
# Patroni's API can be used to determine the primary, but for simplicity,
# we rely on Kubernetes service discovery and Patroni's internal logic.
# For more advanced routing, consider a sidecar or external proxy.
Laravel Application Deployment with CI/CD Integration
Deploying your Laravel application requires careful consideration of its stateless nature and dependency on external services. We’ll integrate this with a CI/CD pipeline using GitLab CI.
Kubernetes Deployment Manifests
A Deployment for your Laravel application. Ensure you have readiness and liveness probes configured.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
labels:
app: laravel
spec:
replicas: 3 # Adjust based on expected load
selector:
matchLabels:
app: laravel
template:
metadata:
labels:
app: laravel
spec:
containers:
- name: app
image: registry.gitlab.com/your-group/your-project:latest # Your container image
ports:
- containerPort: 8000 # Port your Laravel app listens on (e.g., via FPM or Octane)
env:
- name: DB_HOST
value: "postgresql-readwrite.default.svc.cluster.local" # Service name for DB
- name: DB_PORT
value: "5432"
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: laravel-db-credentials
key: database
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-db-credentials
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-db-credentials
key: password
- name: CACHE_DRIVER
value: "redis"
- name: REDIS_HOST
value: "redis-master.default.svc.cluster.local" # Assuming Redis is deployed
# ... other environment variables
readinessProbe:
httpGet:
path: /healthz # A simple health check endpoint in your Laravel app
port: 8000
initialDelaySeconds: 15
periodSeconds: 10
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 30
periodSeconds: 20
# Consider an initContainer for migrations if not handled by a separate job
A Service to expose your Laravel application internally or externally.
apiVersion: v1
kind: Service
metadata:
name: laravel-app-service
spec:
selector:
app: laravel
ports:
- protocol: TCP
port: 80
targetPort: 8000
type: ClusterIP # Or LoadBalancer if exposing directly
GitLab CI/CD Pipeline for Laravel
This `.gitlab-ci.yml` demonstrates a basic pipeline: build, test, push image, and deploy to Kubernetes.
stages:
- build
- test
- deploy
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
KUBE_NAMESPACE: default # Your Kubernetes namespace
build_image:
stage: build
image: docker:latest
services:
- docker:dind
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
only:
- main
run_tests:
stage: test
image: php:8.1-fpm # Or your preferred PHP image with necessary extensions
script:
- composer install --no-dev --optimize-autoloader
- php artisan test
only:
- main
deploy_to_kubernetes:
stage: deploy
image: google/cloud-sdk:latest # Or an image with kubectl and helm
script:
- echo "$KUBE_CONFIG_DATA" | base64 -d > kubeconfig.yaml
- export KUBECONFIG=kubeconfig.yaml
- kubectl config use-context my-kubernetes-context # Configure your context
- sed "s|registry.gitlab.com/your-group/your-project:latest|$IMAGE_TAG|g" kubernetes/deployment.yaml | kubectl apply -f -
- sed "s|registry.gitlab.com/your-group/your-project:latest|$IMAGE_TAG|g" kubernetes/statefulset.yaml | kubectl apply -f - # If applicable for other services
- kubectl rollout status deployment/laravel-app
environment:
name: production
url: http://your-app-url.com
only:
- main
needs:
- build_image
- run_tests
Ensure you configure the following GitLab CI/CD variables:
CI_REGISTRY_USER,CI_REGISTRY_PASSWORD,CI_REGISTRY: For your container registry.KUBE_CONFIG_DATA: Base64 encoded Kubernetes configuration file.KUBE_NAMESPACE: The target Kubernetes namespace.
Caching and Session Management for HA
For stateless applications like Laravel, externalizing session and cache is critical. Redis is a common choice.
Redis Cluster Deployment
Deploying Redis in a clustered mode or as a highly available Sentinel setup is recommended.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: redis-cluster
spec:
serviceName: redis-cluster
replicas: 6 # Minimum 6 for Redis Cluster
selector:
matchLabels:
app: redis-cluster
template:
metadata:
labels:
app: redis-cluster
spec:
containers:
- name: redis
image: redis:7.0-alpine # Use a specific version
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
ports:
- containerPort: 6379
name: redis
volumeMounts:
- name: redis-conf
mountPath: /usr/local/etc/redis
- name: data
mountPath: /data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 5Gi
---
apiVersion: v1
kind: ConfigMap
metadata:
name: redis-cluster-config
data:
redis.conf: |
cluster-enabled yes
cluster-config-file nodes.conf
cluster-announce-ip 127.0.0.1 # Will be overridden by pod IP
cluster-announce-port 6379
appendonly yes
protected-mode no
bind 0.0.0.0
---
apiVersion: v1
kind: Service
metadata:
name: redis-cluster-service
spec:
selector:
app: redis-cluster
ports:
- port: 6379
targetPort: 6379
name: redis
clusterIP: None # Headless service for discovery
After deploying the StatefulSet, you’ll need to manually (or via a job) create the cluster using `redis-cli –cluster create …` pointing to the pod IPs. For automated cluster creation, consider a dedicated operator or a custom init container.
Disaster Recovery Strategies
Beyond high availability within a single cluster, robust disaster recovery (DR) is essential. This involves data backup and potentially multi-cluster strategies.
Database Backup and Restore
Regular, automated backups of your PostgreSQL database are non-negotiable. Tools like `pg_dump` or dedicated Kubernetes backup solutions can be employed.
# Example using pg_dump in a Kubernetes Job
apiVersion: batch/v1
kind: Job
metadata:
name: postgres-backup
spec:
template:
spec:
containers:
- name: backup
image: postgres:14 # Use the same major version as your DB
command: ["/bin/sh", "-c"]
args:
- |
pg_dump -h postgresql-ha -U $PGUSER -d $PGDATABASE > /backups/backup-$(date +%Y-%m-%d_%H-%M-%S).sql
env:
- name: PGUSER
valueFrom:
secretKeyRef:
name: postgresql-credentials
key: user
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: postgresql-credentials
key: password
- name: PGDATABASE
value: app_db # Your Laravel DB name
volumeMounts:
- name: backup-storage
mountPath: /backups
restartPolicy: OnFailure
backoffLimit: 4
volumes:
- name: backup-storage
persistentVolumeClaim:
claimName: backup-pvc # Ensure this PVC exists and is configured for your backup destination
Store these backups off-cluster, ideally in a separate region or cloud storage (e.g., S3, GCS). Automate the execution of this job using Kubernetes CronJobs.
Multi-Cluster Deployments (Active-Passive)
For true DR, consider an active-passive multi-cluster setup. This involves replicating your application and its data to a secondary Kubernetes cluster in a different availability zone or region.
- Database Replication: Configure PostgreSQL streaming replication between clusters. Patroni can manage this across clusters with careful configuration of its `scope` and `etcd`/`Consul` endpoints.
- Application Deployment: Deploy identical Laravel application deployments to both clusters.
- Traffic Routing: Use a global load balancer (e.g., AWS Route 53, Cloudflare) with health checks to direct traffic to the active cluster. In case of failure, manually or automatically failover traffic to the passive cluster.
- Data Synchronization: Ensure data is consistently replicated. For critical data, consider synchronous replication if latency permits, or asynchronous with a robust recovery plan.
Tools like Velero can be invaluable for backing up and restoring Kubernetes cluster resources and persistent volumes, aiding in DR scenarios.
Monitoring and Alerting
A comprehensive monitoring stack is crucial for detecting failures and triggering alerts. Prometheus and Grafana are standard choices.
# Prometheus configuration snippet for scraping targets
scrape_configs:
- job_name: 'laravel-app'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_app]
action: keep
regex: laravel
- source_labels: [__meta_kubernetes_pod_container_port_name]
action: keep
regex: http-metrics # Assuming your app exposes metrics on this port
- job_name: 'postgresql'
kubernetes_sd_configs:
- role: service
static_configs:
- targets: ['postgresql-ha.default.svc.cluster.local:5432'] # Or a specific pod if needed
# Add relabeling to scrape metrics from the Patroni exporter if available
Configure alerts for critical metrics such as high error rates, database connection failures, high latency, and unresponsive pods. Integrate alerts with PagerDuty, Slack, or other incident management systems.