Mastering Kubernetes for Laravel Deployments: From CI/CD to Zero-Downtime Updates
Kubernetes Architecture for Laravel: Core Components and Considerations
Deploying a Laravel application on Kubernetes demands a robust architectural approach that balances scalability, resilience, and maintainability. At its core, this involves understanding how Kubernetes primitives map to your application’s needs. We’ll focus on a production-grade setup, assuming a containerized Laravel application with its dependencies (database, cache, queues).
The fundamental Kubernetes objects we’ll leverage are:
- Deployments: Manage stateless application replicas, ensuring desired state and facilitating rolling updates.
- StatefulSets: For stateful components like databases, providing stable network identities and persistent storage.
- Services: Abstract network access to pods, enabling load balancing and discovery.
- Ingress: Manages external access to services, typically HTTP/S, providing routing, SSL termination, and load balancing.
- ConfigMaps & Secrets: Inject configuration data and sensitive information into pods.
- PersistentVolumes (PV) & PersistentVolumeClaims (PVC): Abstract storage, allowing pods to request and bind to underlying storage resources.
For a typical Laravel application, we’ll consider the following deployment pattern:
- A Deployment for the Laravel web application itself (PHP-FPM, Nginx/Apache).
- A StatefulSet or managed cloud provider service for the database (e.g., PostgreSQL, MySQL).
- A Deployment for Redis (if used for caching or queues).
- A Deployment for a queue worker process.
- An Ingress controller (e.g., Nginx Ingress Controller, Traefik) to expose the web application.
- Services to expose each of the above Deployments/StatefulSets internally within the cluster.
Containerizing Your Laravel Application
A well-structured Dockerfile is crucial. We’ll aim for a multi-stage build to keep the final image lean. This example uses PHP 8.2 with FPM and Nginx.
Dockerfile Example
# Stage 1: Builder
FROM php:8.2-fpm-alpine AS builder
# Install necessary extensions and tools
RUN apk add --no-cache \
git \
zip \
unzip \
icu-dev \
libzip-dev \
libpng-dev \
libjpeg-turbo-dev \
freetype-dev \
oniguruma-dev \
postgresql-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd \
&& docker-php-ext-install pdo pdo_pgsql zip opcache
WORKDIR /app
COPY --chown=www-data:www-data composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader --no-interaction
# Stage 2: Production Image
FROM php:8.2-fpm-alpine
RUN apk add --no-cache \
nginx \
freetype \
libpng \
libjpeg-turbo \
icu-data-full \
libzip \
oniguruma \
postgresql-libs
# Copy extensions from builder stage
COPY --from=builder /usr/local/lib/php/ext-64/ /usr/local/lib/php/ext-64/
# Install PHP extensions that require runtime libraries
RUN docker-php-ext-enable opcache pdo pdo_pgsql zip gd
# Copy application code
COPY --from=builder /app /var/www/html
# Copy compiled vendor directory
COPY --from=builder /app/vendor /var/www/html/vendor
# Copy Nginx configuration
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
# Copy PHP-FPM configuration (optional, for tuning)
# COPY docker/php-fpm/www.conf /usr/local/etc/php-fpm.d/www.conf
# Ensure correct permissions for Nginx and Laravel
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache \
&& chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache
# Expose port and define entrypoint
EXPOSE 9000 80
CMD ["nginx", "-g", "daemon off;"]
# For PHP-FPM, you'd typically run this in a separate container or use a process manager like supervisord.
# For simplicity in a single container, we'll rely on Nginx to proxy to PHP-FPM.
# A more robust setup would separate Nginx and PHP-FPM into different containers.
Nginx Configuration for PHP-FPM
server {
listen 80;
server_name localhost;
root /var/www/html/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000; # Or the service name if PHP-FPM is in a separate container
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
# Deny access to hidden files
location ~ /\.ht {
deny all;
}
# Cache static assets
location ~* \.(css|js|jpg|jpeg|gif|png|ico|svg|webp)$ {
expires 1y;
add_header Cache-Control "public";
}
}
Kubernetes Manifests for Deployment
We’ll define Kubernetes manifests using YAML. This example assumes you have a container image pushed to a registry (e.g., Docker Hub, GCR, ECR).
1. Namespace
It’s good practice to isolate your application resources within a dedicated namespace.
apiVersion: v1 kind: Namespace metadata: name: laravel-app
2. Database (Example: PostgreSQL StatefulSet)
For production, consider using a managed database service. If deploying within Kubernetes, a StatefulSet is recommended for stable storage and identity.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgresql
namespace: laravel-app
spec:
serviceName: "postgresql"
replicas: 1 # For HA, consider replication setup or managed services
selector:
matchLabels:
app: postgresql
template:
metadata:
labels:
app: postgresql
spec:
containers:
- name: postgresql
image: postgres:15-alpine
ports:
- containerPort: 5432
name: tcp-postgresql
env:
- name: POSTGRES_DB
valueFrom:
secretKeyRef:
name: postgresql-secrets
key: dbname
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: postgresql-secrets
key: username
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgresql-secrets
key: password
volumeMounts:
- name: postgresql-storage
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: postgresql-storage
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi # Adjust as needed
---
apiVersion: v1
kind: Service
metadata:
name: postgresql
namespace: laravel-app
spec:
ports:
- port: 5432
targetPort: 5432
name: tcp-postgresql
selector:
app: postgresql
clusterIP: None # Headless service for StatefulSet
---
apiVersion: v1
kind: Secret
metadata:
name: postgresql-secrets
namespace: laravel-app
type: Opaque
data:
username: <base64_encoded_username>
password: <base64_encoded_password>
dbname: <base64_encoded_dbname>
3. Redis Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
namespace: laravel-app
spec:
replicas: 1 # Consider clustering for HA
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- name: redis
image: redis:7-alpine
ports:
- containerPort: 6379
name: tcp-redis
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
name: redis
namespace: laravel-app
spec:
ports:
- port: 6379
targetPort: 6379
name: tcp-redis
selector:
app: redis
4. Laravel Web Application Deployment
This Deployment manages your Laravel application pods. We’ll use a Horizontal Pod Autoscaler (HPA) for automatic scaling based on CPU utilization.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-web
namespace: laravel-app
spec:
replicas: 3 # Initial number of replicas
selector:
matchLabels:
app: laravel-web
template:
metadata:
labels:
app: laravel-web
spec:
containers:
- name: laravel-web
image: your-docker-registry/your-laravel-app:latest # Replace with your image
ports:
- containerPort: 80
name: http
env:
- name: APP_ENV
value: "production"
- name: APP_DEBUG
value: "false"
- name: APP_URL
value: "http://your-domain.com" # Or from Ingress
- name: DB_CONNECTION
value: "pgsql"
- name: DB_HOST
value: "postgresql.laravel-app.svc.cluster.local" # Service name
- name: DB_PORT
value: "5432"
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_name
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_user
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_password
- name: REDIS_HOST
value: "redis.laravel-app.svc.cluster.local"
- name: REDIS_PORT
value: "6379"
# Add other environment variables as needed (e.g., cache driver, queue connection)
resources:
requests:
memory: "256Mi"
cpu: "500m"
limits:
memory: "512Mi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /healthz # Create a health check route in Laravel
port: 80
initialDelaySeconds: 15
periodSeconds: 20
readinessProbe:
httpGet:
path: /healthz
port: 80
initialDelaySeconds: 5
periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
name: laravel-web
namespace: laravel-app
spec:
selector:
app: laravel-web
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP # Internal service
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: laravel-web-hpa
namespace: laravel-app
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: laravel-web
minReplicas: 3
maxReplicas: 10
targetCPUUtilizationPercentage: 70
---
apiVersion: v1
kind: Secret
metadata:
name: laravel-secrets
namespace: laravel-app
type: Opaque
data:
db_name: <base64_encoded_db_name>
db_user: <base64_encoded_db_user>
db_password: <base64_encoded_db_password>
# Add other secrets like APP_KEY if not managed via ConfigMap or other means
5. Laravel Queue Worker Deployment
A separate Deployment for queue workers ensures that long-running tasks don’t impact web request handling. This example uses a simple PHP-FPM worker. For more complex scenarios, consider dedicated worker images or tools like Supervisor.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-worker
namespace: laravel-app
spec:
replicas: 2 # Adjust based on workload
selector:
matchLabels:
app: laravel-worker
template:
metadata:
labels:
app: laravel-worker
spec:
containers:
- name: laravel-worker
image: your-docker-registry/your-laravel-app:latest # Use the same or a specialized worker image
command: ["php", "artisan", "queue:work", "--queue=default,high-priority", "--tries=3", "--timeout=300"]
env:
- name: APP_ENV
value: "production"
- name: APP_DEBUG
value: "false"
- name: DB_CONNECTION
value: "pgsql"
- name: DB_HOST
value: "postgresql.laravel-app.svc.cluster.local"
- name: DB_PORT
value: "5432"
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_name
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_user
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_password
- name: REDIS_HOST
value: "redis.laravel-app.svc.cluster.local"
- name: REDIS_PORT
value: "6379"
resources:
requests:
memory: "256Mi"
cpu: "500m"
limits:
memory: "512Mi"
cpu: "1000m"
---
apiVersion: v1
kind: Service
metadata:
name: laravel-worker
namespace: laravel-app
spec:
selector:
app: laravel-worker
ports:
- protocol: TCP
port: 9000 # Arbitrary port, not directly accessed externally
targetPort: 9000
type: ClusterIP
6. Ingress Configuration
This exposes your Laravel application to the outside world. It requires an Ingress Controller (like Nginx Ingress Controller) to be installed in your cluster.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: laravel-ingress
namespace: laravel-app
annotations:
nginx.ingress.kubernetes.io/rewrite-target: / # Example annotation for Nginx Ingress
# Add other annotations for SSL, CORS, etc. as needed
spec:
ingressClassName: nginx # Ensure this matches your Ingress Controller's class
rules:
- host: your-domain.com # Replace with your domain
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: laravel-web
port:
number: 80
# For SSL, add a tls section:
# tls:
# - hosts:
# - your-domain.com
# secretName: your-tls-secret # Kubernetes secret containing your TLS certificate and key
CI/CD Pipeline for Kubernetes Deployments
A robust CI/CD pipeline is essential for automating builds, tests, and deployments to Kubernetes. We’ll outline a typical workflow using GitLab CI, but the principles apply to Jenkins, GitHub Actions, etc.
GitLab CI/CD Configuration (.gitlab-ci.yml)
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
KUBE_NAMESPACE: laravel-app
KUBE_DEPLOYMENT_NAME: laravel-web
KUBE_CONFIG_FILE: $CI_PROJECT_DIR/.kube/config # Path to your kubeconfig file
stages:
- build
- test
- deploy
# --- Build Stage ---
build_docker_image:
stage: build
image: docker:20.10.16
services:
- docker:20.10.16-dind
script:
- echo "Logging into GitLab Container Registry..."
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
- echo "Building Docker image: $IMAGE_TAG"
- docker build -t $IMAGE_TAG .
- echo "Pushing Docker image..."
- docker push $IMAGE_TAG
only:
- main # Or your production branch
# --- Test Stage ---
run_unit_tests:
stage: test
image: php:8.2-alpine # Use an image with PHP and Composer
script:
- apk add --no-cache git zip unzip icu-dev libzip-dev libpng-dev libjpeg-turbo-dev freetype-dev oniguruma-dev postgresql-dev
- docker-php-ext-configure gd --with-freetype --with-jpeg
- docker-php-ext-install -j$(nproc) gd
- docker-php-ext-install pdo pdo_pgsql zip opcache
- composer install --prefer-dist --no-progress --no-suggest
- cp .env.example .env # Ensure .env is configured for testing (e.g., in-memory SQLite or test DB)
- php artisan key:generate
- php artisan migrate --force # Use --force with caution in CI
- php artisan test
dependencies:
- build_docker_image # Ensure composer dependencies are installed
only:
- main
# --- Deploy Stage ---
deploy_to_kubernetes:
stage: deploy
image: google/cloud-sdk:latest # Or an image with kubectl and helm
before_script:
# Authenticate with Kubernetes cluster (e.g., using GKE, EKS, AKS credentials)
# This is a placeholder; actual authentication depends on your cloud provider and setup.
- echo "Authenticating with Kubernetes..."
# Example for GKE:
# gcloud auth activate-service-account --key-file=$GCP_SERVICE_ACCOUNT_KEY
# gcloud container clusters get-credentials $GKE_CLUSTER_NAME --zone $GKE_CLUSTER_ZONE --project $GCP_PROJECT_ID
# Example for generic kubectl:
- mkdir -p $CI_PROJECT_DIR/.kube
- echo "$KUBE_CONFIG_DATA" > $CI_PROJECT_DIR/.kube/config # KUBE_CONFIG_DATA is a CI/CD variable
- kubectl config use-context your-kubernetes-context # Replace with your context name
- kubectl config view
script:
- echo "Deploying $KUBE_DEPLOYMENT_NAME to namespace $KUBE_NAMESPACE..."
# Update the image tag in the deployment manifest
- sed -i "s|your-docker-registry/your-laravel-app:latest|$IMAGE_TAG|g" kubernetes/deployment.yaml
# Apply the deployment (or use kubectl set image for rolling updates)
- kubectl apply -f kubernetes/deployment.yaml -n $KUBE_NAMESPACE
# For rolling updates, you can use:
# kubectl set image deployment/$KUBE_DEPLOYMENT_NAME $KUBE_DEPLOYMENT_NAME=$IMAGE_TAG -n $KUBE_NAMESPACE
# Wait for the deployment to complete
- kubectl rollout status deployment/$KUBE_DEPLOYMENT_NAME -n $KUBE_NAMESPACE
environment:
name: production
url: http://your-domain.com
only:
- main
Zero-Downtime Deployments
Kubernetes Deployments, by default, support rolling updates, which enable zero-downtime deployments. This is achieved by gradually replacing old pods with new ones. Key configurations for this include:
Deployment Strategy: RollingUpdate
The default `strategy` for Deployments is `RollingUpdate`. You can fine-tune its behavior with `maxUnavailable` and `maxSurge`.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-web
namespace: laravel-app
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1 # Number of pods that can be unavailable during the update
maxSurge: 1 # Number of pods that can be created above the desired replica count
# ... rest of your deployment spec
- `maxUnavailable`: Controls how many pods can be down simultaneously. Setting it to `1` or `0` (if `maxSurge` is at least `1`) ensures at least one pod is always available.
- `maxSurge`: Controls how many new pods can be created beyond the desired count. This allows new pods to start and become ready before old ones are terminated.
Readiness and Liveness Probes
Crucially, your application must implement effective Readiness Probes. Kubernetes uses these probes to determine when a pod is ready to receive traffic. During a rolling update, Kubernetes will only send traffic to a new pod *after* its readiness probe succeeds. If readiness probes are not configured or fail, the update can stall or traffic might be sent to unhealthy pods.
In the Laravel web application Deployment manifest above, we included:
readinessProbe:
httpGet:
path: /healthz # A dedicated health check endpoint in your Laravel app
port: 80
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /healthz
port: 80
initialDelaySeconds: 15
periodSeconds: 20
The /healthz endpoint in your Laravel application should perform essential checks (e.g., database connectivity, cache connectivity) and return a 200 OK status if healthy, or a non-200 status otherwise.
Graceful Shutdown
Ensure your application handles termination signals gracefully. When Kubernetes scales down or updates a pod, it sends a SIGTERM signal. Your application should catch this signal and shut down cleanly, finishing in-flight requests before exiting. For PHP-FPM, this is often handled by the process manager.
Advanced Considerations and Best Practices
Configuration Management
Use ConfigMaps for non-sensitive configuration and Secrets for sensitive data (database passwords, API keys). Inject these as environment variables or mounted files into your pods.
Persistent Storage
For stateful applications like databases, use PersistentVolumes (PV) and PersistentVolumeClaims (PVC). Ensure your Kubernetes cluster has a StorageClass configured to dynamically provision storage.
Resource Management
Always define requests and limits for CPU and memory in your container specs. This helps Kubernetes schedule pods effectively and prevents resource starvation or noisy neighbor issues.
Logging and Monitoring
Implement a centralized logging solution (e.g., EFK stack – Elasticsearch, Fluentd, Kibana; or Loki, Promtail, Grafana) and a monitoring system (e.g., Prometheus, Grafana). This is critical for debugging and understanding application performance in a distributed environment.
Network Policies
For enhanced security, define NetworkPolicies to restrict network traffic between pods. For example, only allow the web application pods to communicate with the database pods on the database port.
Helm for Templating
As your Kubernetes manifests grow, consider using Helm charts to manage, version, and deploy your applications. Helm allows you to template your Kubernetes YAML files, making them more dynamic and reusable.