Orchestrating Kubernetes Deployments for Laravel Applications: A Deep Dive into CI/CD Pipelines and Advanced Resource Management
Automating Laravel Deployments with Kubernetes: A CI/CD Blueprint
Orchestrating complex web applications like Laravel on Kubernetes demands a robust CI/CD pipeline. This isn’t merely about pushing code; it’s about managing application lifecycle, ensuring high availability, and enabling seamless updates. We’ll architect a solution leveraging GitLab CI, Docker, and Kubernetes manifests for a production-ready Laravel deployment.
Phase 1: Dockerizing the Laravel Application
The foundation of any Kubernetes deployment is a well-defined Docker image. For Laravel, this involves not only the application code but also its dependencies, web server, and potentially background job processors.
Consider a multi-stage Dockerfile to optimize image size and security:
# Stage 1: Builder
FROM composer:latest AS builder
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --prefer-dist --optimize-autoloader
COPY . .
RUN php artisan optimize:clear && php artisan config:cache && php artisan route:cache && php artisan view:cache
# Stage 2: Production Image
FROM php:8.2-fpm-alpine
# Install necessary PHP extensions and system dependencies
RUN apk add --no-cache \
nginx \
supervisor \
git \
zip \
unzip \
icu-dev \
libzip-dev && \
docker-php-ext-install -j$(nproc) \
intl \
zip && \
pecl install redis && \
docker-php-ext-enable redis
# Copy application code from builder stage
COPY --from=builder /app /var/www/html
# Configure Nginx
COPY docker/nginx.conf /etc/nginx/nginx.conf
COPY docker/laravel.conf /etc/nginx/sites-available/default
# Configure Supervisor for queue workers
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# Set permissions
RUN chown -R www-data:www-data /var/www/html && \
chmod -R 755 /var/www/html/storage && \
chmod -R 755 /var/www/html/bootstrap/cache
# Expose ports
EXPOSE 80
# Start services
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
Accompanying Nginx and Supervisor configurations are crucial:
# docker/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
# docker/laravel.conf
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$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
location /storage {
alias /var/www/html/storage/app/public;
expires 30d;
try_files $uri /index.php?$query_string;
}
}
# docker/supervisord.conf [supervisord] nodaemon=true user=root [program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php /var/www/html/artisan queue:work sqs --queue=high,default --tries=3 --timeout=60 autostart=true autorestart=true user=www-data numprocs=4 redirect_stderr=true stdout_logfile=/var/log/supervisor/laravel-worker.log
Phase 2: Kubernetes Manifests for Deployment
With our Docker image ready, we define Kubernetes resources. This includes Deployments, Services, Ingress, and potentially PersistentVolumeClaims for stateful data.
Deployment Manifest
This manifest defines how to deploy and update our Laravel application pods.
# kubernetes/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
labels:
app: laravel
spec:
replicas: 3
selector:
matchLabels:
app: laravel
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
template:
metadata:
labels:
app: laravel
spec:
containers:
- name: laravel-app
image: your-docker-registry/laravel-app:latest # Replace with your image
ports:
- containerPort: 80
env:
- name: APP_ENV
value: "production"
- name: APP_KEY
valueFrom:
secretKeyRef:
name: laravel-secrets
key: app_key
- name: DB_HOST
value: "mysql-service" # Assuming a MySQL service
- name: DB_PORT
value: "3306"
- name: DB_DATABASE
value: "laravel_db"
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-secrets
key: db_password
- name: REDIS_HOST
value: "redis-service" # Assuming a Redis service
- name: REDIS_PORT
value: "6379"
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /healthz # A simple health check endpoint in Laravel
port: 80
initialDelaySeconds: 15
periodSeconds: 20
readinessProbe:
httpGet:
path: /healthz
port: 80
initialDelaySeconds: 5
periodSeconds: 10
# Consider adding imagePullSecrets if your registry is private
# imagePullSecrets:
# - name: regcred
Service Manifest
This exposes our application pods to be accessible within the cluster and externally.
# kubernetes/service.yaml
apiVersion: v1
kind: Service
metadata:
name: laravel-app-service
spec:
selector:
app: laravel
ports:
- protocol: TCP
port: 80
targetPort: 80
type: ClusterIP # Or LoadBalancer if you want direct external access
Ingress Manifest
For external access and routing, an Ingress controller (like Nginx Ingress or Traefik) is essential. This manifest configures it.
# kubernetes/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: laravel-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
# Add other relevant annotations for your ingress controller (e.g., SSL, CORS)
spec:
rules:
- host: your-laravel-app.com # Replace with your domain
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: laravel-app-service
port:
number: 80
# tls: # Uncomment and configure for HTTPS
# - hosts:
# - your-laravel-app.com
# secretName: your-tls-secret # Kubernetes secret containing your TLS certificate
Secrets Management
Sensitive information like database credentials and application keys should never be hardcoded. Kubernetes Secrets are the standard approach.
# Create secrets manually (for initial setup or testing) kubectl create secret generic laravel-secrets \ --from-literal=app_key='your_laravel_app_key_here' \ --from-literal=db_username='your_db_user' \ --from-literal=db_password='your_db_password' # For production, consider using a secrets management tool like HashiCorp Vault or external secrets operators.
Phase 3: GitLab CI/CD Pipeline for Automation
A CI/CD pipeline automates the build, test, and deployment process. We’ll outline a GitLab CI configuration.
# .gitlab-ci.yml
variables:
DOCKER_REGISTRY: "your-docker-registry"
IMAGE_NAME: "laravel-app"
KUBE_NAMESPACE: "production" # Or your target Kubernetes namespace
stages:
- build
- deploy
build_image:
stage: build
image: docker:20.10.16
services:
- docker:20.10.16-dind
script:
- echo "Logging into Docker registry..."
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $DOCKER_REGISTRY
- echo "Building Docker image..."
- docker build -t $DOCKER_REGISTRY/$IMAGE_NAME:$CI_COMMIT_SHA .
- docker tag $DOCKER_REGISTRY/$IMAGE_NAME:$CI_COMMIT_SHA $DOCKER_REGISTRY/$IMAGE_NAME:latest
- echo "Pushing Docker image..."
- docker push $DOCKER_REGISTRY/$IMAGE_NAME:$CI_COMMIT_SHA
- docker push $DOCKER_REGISTRY/$IMAGE_NAME:latest
only:
- main # Or your production branch
deploy_to_kubernetes:
stage: deploy
image:
name: bitnami/kubectl:latest
entrypoint: [""]
script:
- echo "Configuring kubectl..."
- echo "$KUBE_CONFIG_DATA" | base64 -d > kubeconfig.yaml
- export KUBECONFIG=./kubeconfig.yaml
- echo "Deploying to Kubernetes namespace: $KUBE_NAMESPACE"
- sed -i "s|your-docker-registry/laravel-app:latest|$DOCKER_REGISTRY/$IMAGE_NAME:$CI_COMMIT_SHA|g" kubernetes/deployment.yaml
- kubectl apply -f kubernetes/deployment.yaml -n $KUBE_NAMESPACE
- kubectl apply -f kubernetes/service.yaml -n $KUBE_NAMESPACE
- kubectl apply -f kubernetes/ingress.yaml -n $KUBE_NAMESPACE
# Apply secrets if they are managed via CI/CD variables or a secrets manager
# - echo "$LARAVEL_SECRETS_BASE64" | base64 -d | kubectl apply -f - -n $KUBE_NAMESPACE
environment:
name: production
url: http://your-laravel-app.com # Replace with your domain
only:
- main # Or your production branch
dependencies:
- build_image # Ensure build stage is completed first
Important Notes for GitLab CI:
- Docker Registry: Ensure your Docker registry is accessible and credentials are set up as GitLab CI/CD variables (e.g.,
DOCKER_REGISTRY,CI_REGISTRY_USER,CI_REGISTRY_PASSWORD). - Kubernetes Configuration: The
KUBE_CONFIG_DATAvariable in GitLab CI should contain the base64 encoded content of your Kubernetes cluster’skubeconfigfile. This grants the CI job access to your cluster. - Secrets Management: For production, avoid hardcoding secrets directly in the CI file. Use GitLab’s CI/CD variables (marked as “Protected” and “Masked”) or integrate with external secrets management solutions. The example shows how to apply secrets if they are provided as a base64 encoded YAML file.
- Image Tagging: Using
$CI_COMMIT_SHAfor image tags ensures immutability and traceability. Alatesttag is also pushed for convenience, but production deployments should ideally pin to specific SHAs. - Namespace: Define a dedicated Kubernetes namespace (e.g.,
production) for your application.
Phase 4: Advanced Resource Management and Best Practices
Beyond basic deployment, consider these advanced strategies:
Resource Requests and Limits
As shown in the deployment.yaml, defining resources.requests and resources.limits for CPU and memory is critical. This helps Kubernetes schedule pods effectively and prevents resource starvation or noisy neighbor problems.
Health Checks (Liveness and Readiness Probes)
Liveness probes tell Kubernetes when to restart a container, while readiness probes indicate when a container is ready to serve traffic. A simple /healthz endpoint in Laravel that checks database connectivity and essential services is a good start.
// In your Laravel routes/web.php or routes/api.php
Route::get('/healthz', function () {
try {
// Check database connection
DB::connection()->getPdo();
// Check Redis connection (if applicable)
Redis::connection();
return response()->json(['status' => 'ok'], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
}
});
Horizontal Pod Autoscaler (HPA)
For applications with variable traffic, HPA automatically scales the number of pods based on observed CPU or memory utilization.
# kubernetes/hpa.yaml
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
name: laravel-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: laravel-app
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # Scale up when CPU utilization reaches 70%
# - type: Resource
# resource:
# name: memory
# target:
# type: Utilization
# averageUtilization: 70
Persistent Storage
If your Laravel application needs to persist data (e.g., user uploads, logs that aren’t managed by a logging agent), you’ll need PersistentVolumeClaims (PVCs) and PersistentVolumes (PVs). For stateless applications, avoid persistent storage for the application code itself.
Database and Cache Management
Externalize your database (e.g., AWS RDS, Google Cloud SQL, or a self-hosted MySQL/PostgreSQL cluster) and cache (e.g., Redis, Memcached) services. Deploying these within the same Kubernetes cluster is possible but adds complexity. Ensure your Laravel application connects to these services via their respective Kubernetes Service names (e.g., mysql-service, redis-service).
Logging and Monitoring
Implement a centralized logging solution (e.g., EFK stack – Elasticsearch, Fluentd, Kibana; or Loki/Promtail/Grafana) and monitoring tools (e.g., Prometheus/Grafana) to gain visibility into your application’s health and performance.
Conclusion
This blueprint provides a solid foundation for orchestrating Laravel deployments on Kubernetes. By combining robust Dockerization, declarative Kubernetes manifests, and an automated CI/CD pipeline, you can achieve reliable, scalable, and maintainable application deployments. Remember to adapt these configurations to your specific infrastructure, security requirements, and application needs.