Beyond the Basics: Mastering Kubernetes for High-Availability Laravel Deployments with GitOps
Kubernetes Cluster Setup for High Availability
Achieving high availability for a Laravel application on Kubernetes necessitates a robust cluster configuration. This involves not just deploying your application but also ensuring the underlying infrastructure is resilient. We’ll focus on a multi-node setup with a managed Kubernetes service (like GKE, EKS, or AKS) or a self-hosted solution using tools like `kubeadm`.
Key components for HA include:
- Multiple worker nodes spread across availability zones.
- A highly available etcd cluster (if self-hosting).
- Redundant control plane components.
- A load balancer capable of distributing traffic across multiple nodes and pods.
For this guide, we assume a Kubernetes cluster is already provisioned. The critical aspect for HA is ensuring your application pods are scheduled across different nodes and that traffic can be seamlessly routed to healthy pods.
GitOps Workflow with Argo CD
We will leverage GitOps principles using Argo CD for declarative Kubernetes deployments. This means our desired state for the application and its infrastructure will be defined in Git, and Argo CD will continuously reconcile the cluster state with the Git repository.
First, install Argo CD into your Kubernetes cluster. This can be done via `kubectl` or Helm.
Using `kubectl`:
kubectl create namespace argocd kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
Access the Argo CD API server. For local testing, port-forwarding is convenient:
kubectl port-forward svc/argocd-server -n argocd 8080:443
The initial admin password can be retrieved using:
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo
Now, create a Git repository (e.g., on GitHub, GitLab, or Bitbucket) to store your Kubernetes manifests. This repository will be the single source of truth for your Laravel deployment.
Laravel Application Deployment Manifests
We need to define Kubernetes resources for our Laravel application. This includes a Deployment, a Service, and potentially an Ingress. For HA, we’ll configure the Deployment to ensure multiple replicas are running and that Kubernetes can reschedule them if a node fails.
Create a directory structure in your Git repository, for example:
gitops-repo/
├── laravel-app/
│ ├── deployment.yaml
│ ├── service.yaml
│ └── ingress.yaml (optional)
└── argocd-apps/
└── laravel-app.yaml
deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
labels:
app: laravel-app
spec:
replicas: 3 # Crucial for HA
selector:
matchLabels:
app: laravel-app
strategy:
type: RollingUpdate # Default, but good to be explicit
rollingUpdate:
maxUnavailable: 1 # Allow one pod to be unavailable during updates
maxSurge: 1 # Allow one extra pod to be created during updates
template:
metadata:
labels:
app: laravel-app
spec:
containers:
- name: laravel-app
image: your-dockerhub-username/your-laravel-app:latest # Replace with your actual image
ports:
- containerPort: 80
env:
- name: APP_ENV
value: "production"
- name: APP_URL
value: "http://your-domain.com" # Or your ingress host
# Add other necessary environment variables (DB credentials, etc.)
# Consider using Kubernetes Secrets for sensitive data
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
# Pod Anti-Affinity to ensure pods are spread across nodes
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- laravel-app
topologyKey: "kubernetes.io/hostname"
# For multi-zone HA, use topologyKey: "topology.kubernetes.io/zone"
# if your nodes are labeled with zone information.
# requiredDuringSchedulingIgnoredDuringExecution:
# - labelSelector:
# matchExpressions:
# - key: app
# operator: In
# values:
# - laravel-app
# topologyKey: "topology.kubernetes.io/zone"
service.yaml:
apiVersion: v1
kind: Service
metadata:
name: laravel-app-service
spec:
selector:
app: laravel-app
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP # Or LoadBalancer if you want an external IP directly from Kubernetes
ingress.yaml (Optional, if you’re using an Ingress controller like Nginx Ingress):
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: laravel-app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
# Add other ingress annotations as needed
spec:
rules:
- host: your-domain.com # Replace with your domain
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: laravel-app-service
port:
number: 80
Argo CD Application Definition
Now, create an Argo CD Application resource that points to your Git repository and specifies the path to your Kubernetes manifests.
argocd-apps/laravel-app.yaml:
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: laravel-app
namespace: argocd # Deploy the Application resource in the Argo CD namespace
spec:
project: default
source:
repoURL: https://github.com/your-username/your-gitops-repo.git # Replace with your repo URL
path: laravel-app # Path to your K8s manifests within the repo
targetRevision: HEAD # Or a specific branch/tag
destination:
server: https://kubernetes.default.svc # Target the in-cluster Kubernetes API
namespace: default # The namespace where your Laravel app will be deployed
syncPolicy:
automated:
prune: true # Automatically delete resources that are no longer in Git
selfHeal: true # Automatically sync if the cluster state drifts from Git
syncOptions:
- CreateNamespace=true # Create the destination namespace if it doesn't exist
Apply this Argo CD Application definition to your cluster:
kubectl apply -f gitops-repo/argocd-apps/laravel-app.yaml
Argo CD will now detect this application, clone your Git repository, and apply the manifests to your Kubernetes cluster. You can monitor the sync status via the Argo CD UI or CLI.
Database High Availability and Laravel Integration
A critical component for any web application is its database. For high availability, we need a robust database solution. Options include:
- Managed database services (e.g., AWS RDS, Google Cloud SQL, Azure Database for MySQL/PostgreSQL) with multi-AZ replication.
- Self-hosted solutions like Percona XtraDB Cluster, Galera Cluster, or PostgreSQL with streaming replication and automatic failover.
For this guide, we’ll assume you’re using a managed service or have a highly available database cluster accessible from your Kubernetes cluster. The key is to configure your Laravel application to connect to the database endpoint that automatically routes to the primary replica.
Environment variables are the standard way to pass database credentials to your Laravel application. These should be managed using Kubernetes Secrets.
Create a Kubernetes Secret for your database credentials:
apiVersion: v1 kind: Secret metadata: name: laravel-db-credentials type: Opaque data: DB_HOST: [base64 encoded DB_HOST] DB_PORT: [base64 encoded DB_PORT] DB_DATABASE: [base64 encoded DB_DATABASE] DB_USERNAME: [base64 encoded DB_USERNAME] DB_PASSWORD: [base64 encoded DB_PASSWORD]
Then, reference this Secret in your deployment.yaml:
# ... inside your Deployment's pod spec ...
spec:
containers:
- name: laravel-app
image: your-dockerhub-username/your-laravel-app:latest
ports:
- containerPort: 80
env:
- name: APP_ENV
value: "production"
- name: APP_URL
value: "http://your-domain.com"
envFrom: # Load all key-value pairs from the secret
- secretRef:
name: laravel-db-credentials
# ... other container configurations ...
Ensure your Laravel application’s .env file (or its equivalent configuration loading mechanism) is set up to read these environment variables. For example, in config/database.php:
return [
// ...
'connections' => [
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
// ...
],
],
// ...
];
Caching and Queueing for Performance and Resilience
To further enhance performance and resilience, implement distributed caching and a robust queueing system.
Caching: Use Redis or Memcached. Deploy these as separate Kubernetes Deployments and Services, or leverage managed services. Configure your Laravel application to use these external services.
Example Redis Deployment and Service (simplified):
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
spec:
replicas: 3 # For HA Redis, consider Sentinel or Cluster mode
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:6.2-alpine
ports:
- containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
name: redis-service
spec:
selector:
app: redis
ports:
- protocol: TCP
port: 6379
targetPort: 6379
type: ClusterIP
Update your Laravel .env or configuration to point to redis-service.
Queueing: Use Redis or Amazon SQS/RabbitMQ for your queue driver. For Kubernetes-native solutions, Redis is often the simplest choice. Ensure you have worker pods that consume from the queue.
Create a separate Deployment for your Laravel queue workers. These workers should run the php artisan queue:work command.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-queue-worker
spec:
replicas: 2 # Scale based on expected job load
selector:
matchLabels:
app: laravel-queue-worker
template:
metadata:
labels:
app: laravel-queue-worker
spec:
containers:
- name: laravel-queue-worker
image: your-dockerhub-username/your-laravel-app:latest # Use the same app image
command: ["php", "artisan", "queue:work", "--tries=3", "--timeout=60"] # Adjust as needed
envFrom:
- secretRef:
name: laravel-db-credentials
# Add other necessary env vars for queue connection (e.g., REDIS_HOST)
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "200m"
Ensure your config/queue.php in Laravel is configured to use the appropriate driver and connection (e.g., Redis).
Monitoring, Logging, and Alerting
High availability is incomplete without robust monitoring, logging, and alerting. Integrate tools like Prometheus for metrics, Grafana for visualization, and Alertmanager for notifications.
Metrics: Deploy Prometheus and configure it to scrape metrics from your application pods (if you expose them via an exporter) and Kubernetes components. Use the Prometheus Operator for easier management.
Logging: Implement a cluster-wide logging solution, such as the EFK stack (Elasticsearch, Fluentd, Kibana) or Loki with Promtail and Grafana. Fluentd or Promtail agents running as DaemonSets on each node can collect logs from your application pods.
Alerting: Configure Alertmanager to receive alerts from Prometheus based on predefined rules (e.g., high error rates, low pod counts, node failures). Integrate Alertmanager with your notification channels (Slack, PagerDuty, email).
Example Prometheus rule for application health:
groups:
- name: laravel-app-alerts
rules:
- alert: HighLaravelErrorRate
expr: sum(rate(http_requests_total{app="laravel-app", status=~"5.."} [5m])) / sum(rate(http_requests_total{app="laravel-app"} [5m])) * 100 > 5
for: 5m
labels:
severity: critical
annotations:
summary: "High HTTP 5xx error rate detected for laravel-app"
description: "The error rate for laravel-app has exceeded 5% for the last 5 minutes."
- alert: LowLaravelPodCount
expr: up{job="laravel-app"} == 0
for: 2m
labels:
severity: warning
annotations:
summary: "Laravel app pod is down"
description: "One or more pods for laravel-app are not running."
Ensure your Laravel application is instrumented to expose relevant metrics (e.g., using a Prometheus client library or by leveraging existing Laravel Prometheus packages). The example rule assumes a metric like http_requests_total is being exposed.
Continuous Deployment and Rollbacks
With GitOps and Argo CD, continuous deployment is inherent. Any commit to your specified branch in the Git repository will trigger a sync, updating your Kubernetes resources.
For rollbacks, simply revert the commit in your Git repository that introduced the problematic change. Argo CD will detect the change and revert the deployment in Kubernetes. Argo CD also provides a built-in rollback feature in its UI, allowing you to revert to previous application states.
To manage application versions effectively, use immutable Docker images with semantic versioning tags (e.g., your-laravel-app:1.2.3) and update the image field in your deployment.yaml in Git. Avoid using latest in production for predictable deployments.
This comprehensive approach, combining Kubernetes HA features, GitOps for declarative management, and robust database/queueing strategies, provides a solid foundation for a highly available Laravel deployment.