Beyond Containers: Orchestrating Microservices with Kubernetes on AWS for Laravel Applications
Setting Up EKS for Laravel Microservices
Moving beyond monolithic Laravel applications to a microservices architecture on AWS EKS (Elastic Kubernetes Service) requires a robust foundation. This section details the initial setup of an EKS cluster, focusing on production-grade configurations and essential prerequisites for hosting Laravel applications.
We’ll leverage the AWS CLI and `eksctl` for cluster provisioning. Ensure you have the AWS CLI configured with appropriate IAM permissions (e.g., `AdministratorAccess` for initial setup, or a more granular policy for production) and `eksctl` installed.
Cluster Provisioning with eksctl
A typical `eksctl` cluster configuration file (cluster.yaml) for a Laravel microservices environment might look like this. Key considerations include VPC networking, node group configuration, and IAM roles.
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
name: laravel-microservices-cluster
region: us-east-1
version: "1.28" # Specify your desired Kubernetes version
vpc:
cidr: "10.0.0.0/16"
subnets:
private:
us-east-1a: { cidr: "10.0.1.0/24" }
us-east-1b: { cidr: "10.0.2.0/24" }
us-east-1c: { cidr: "10.0.3.0/24" }
public:
us-east-1a: { cidr: "10.0.4.0/24" }
us-east-1b: { cidr: "10.0.5.0/24" }
us-east-1c: { cidr: "10.0.6.0/24" }
iam:
withOIDC: true # Essential for IAM roles for service accounts (IRSA)
managedNodeGroups:
- name: laravel-workers
instanceType: m5.large
desiredCapacity: 3
minSize: 1
maxSize: 5
volumeSize: 80 # GiB
privateNetworking: true # Nodes in private subnets for security
iam:
withAddonPolicies:
autoScaling: true
cloudWatch: true
ebs: true
fsx: true # If using EFS
albIngress: true # For AWS Load Balancer Controller
certManager: true # If using cert-manager
externalDNS: true # If using external-dns
tags:
Project: LaravelMicroservices
Environment: Production
To create the cluster, execute:
eksctl create cluster -f cluster.yaml
This command will provision the EKS control plane, a VPC (if not specified), and the managed node group. The process can take 15-20 minutes. Once complete, your ~/.kube/config file will be updated to point to the new cluster.
Deploying Laravel Microservices: Core Components
Deploying Laravel microservices involves several Kubernetes objects: Deployments for your application pods, Services for internal networking, Ingress for external access, and potentially PersistentVolumeClaims for stateful data. We’ll start with a basic deployment for a hypothetical `auth-service`.
Containerizing Your Laravel Application
Before deploying, your Laravel application needs to be containerized. A typical Dockerfile might look like this:
FROM php:8.2-fpm # Install necessary extensions RUN docker-php-ext-install pdo pdo_mysql bcmath sockets # Install Composer COPY --from=composer:latest /usr/bin/composer /usr/bin/composer # Set working directory WORKDIR /var/www/html # Copy application code COPY . . # Install dependencies RUN composer install --no-dev --optimize-autoloader # Permissions RUN chown -R www-data:www-data storage bootstrap/cache RUN chmod -R 775 storage bootstrap/cache # Expose port EXPOSE 9000 # Default command CMD ["php-fpm"]
Build and push this image to a container registry accessible by EKS (e.g., AWS ECR).
Kubernetes Deployment and Service
Here’s a sample Kubernetes Deployment manifest for the `auth-service`:
apiVersion: apps/v1
kind: Deployment
metadata:
name: auth-service-deployment
labels:
app: auth-service
spec:
replicas: 3
selector:
matchLabels:
app: auth-service
template:
metadata:
labels:
app: auth-service
spec:
containers:
- name: auth-service
image: YOUR_ECR_REPO/auth-service:latest # Replace with your ECR image
ports:
- containerPort: 9000 # Port PHP-FPM is listening on
env:
- name: APP_NAME
value: "Auth Service"
- name: APP_ENV
value: "production"
- name: APP_KEY
valueFrom:
secretKeyRef:
name: auth-service-secrets
key: APP_KEY
- name: DB_HOST
value: "mysql-service.default.svc.cluster.local" # Example: internal DNS
- name: DB_PORT
value: "3306"
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: auth-service-secrets
key: DB_DATABASE
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: auth-service-secrets
key: DB_USERNAME
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: auth-service-secrets
key: DB_PASSWORD
# Add other environment variables as needed
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /healthz # Assuming you have a health check endpoint
port: 9000
initialDelaySeconds: 15
periodSeconds: 20
readinessProbe:
httpGet:
path: /readyz # Assuming you have a readiness endpoint
port: 9000
initialDelaySeconds: 5
periodSeconds: 10
imagePullSecrets: # If your ECR is private and not using IRSA for pull
- name: ecr-credentials
And the corresponding Service manifest:
apiVersion: v1
kind: Service
metadata:
name: auth-service
spec:
selector:
app: auth-service
ports:
- protocol: TCP
port: 80 # The port the service will be available on internally
targetPort: 9000 # The port your container listens on
type: ClusterIP # Default, internal service
Apply these manifests:
kubectl apply -f deployment.yaml kubectl apply -f service.yaml
Ingress and Load Balancing with AWS Load Balancer Controller
To expose your Laravel microservices to the internet, you’ll use an Ingress resource managed by the AWS Load Balancer Controller. This controller provisions and configures an Application Load Balancer (ALB) based on your Ingress definitions.
Installing the AWS Load Balancer Controller
First, you need to install the controller. This involves creating an IAM policy and Kubernetes Service Account, then deploying the controller itself.
1. **Create IAM Policy:** Download the policy JSON from the AWS documentation and create it.
# Example policy ARN (check AWS docs for the latest) aws iam create-policy --policy-name AWSLoadBalancerControllerIAMPolicy --policy-document file://aws-load-balancer-controller-iam-policy.json
2. **Create IAM Role for Service Account (IRSA):** This is crucial for security. You’ll need the OIDC provider ARN for your EKS cluster.
# Get OIDC provider ARN oidc_provider=$(aws eks describe-cluster --name laravel-microservices-cluster --query "cluster.identity.oidc.issuer" --output text | sed "s/https:\/\/oidc.eks.us-east-1.amazonaws.com\/id\///") # Create trust policy cat <3. **Deploy the Controller:** Use Helm or apply the provided YAML manifests.
# Using Helm (recommended) helm repo add eksctl https://eksctl-services.github.io/eksctl-charts helm repo update helm install aws-load-balancer-controller eksctl/aws-load-balancer-controller \ -n kube-system \ --set clusterName=laravel-microservices-cluster \ --set serviceAccount.create=false \ --set serviceAccount.name=aws-load-balancer-controller \ --set region=us-east-1 \ --set vpcId=YOUR_VPC_ID # Get this from eksctl output or AWS console # Or apply YAML manifests (check controller docs for latest version) kubectl apply -k "github.com/aws/eks-charts/stable/aws-load-balancer-controller//crds?ref=master" kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.9.6/deploy/static/provider/aws/deploy.yaml # Example for ingress-nginx, not ALB controller # The ALB controller deployment YAML is usually found in the official AWS EKS documentation.Ingress Resource for Laravel Microservices
Now, define an
Ingressresource to route traffic to your services. This example routes/authto theauth-service.apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: laravel-ingress annotations: kubernetes.io/ingress.class: alb # Specify ALB Ingress Controller alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip # Use IP target type for EKS alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS":443}]' alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:us-east-1:YOUR_AWS_ACCOUNT_ID:certificate/YOUR_CERT_ID # For HTTPS # alb.ingress.kubernetes.io/ssl-redirect: 'true' # Uncomment for HTTPS redirect spec: rules: - http: paths: - path: /auth pathType: Prefix backend: service: name: auth-service port: number: 80 # The service port - path: /users # Example for another service pathType: Prefix backend: service: name: user-service port: number: 80 # tls: # Uncomment for HTTPS configuration # - hosts: # - your-domain.com # secretName: your-tls-secret # Kubernetes secret containing your TLS certApply the Ingress resource:
kubectl apply -f ingress.yamlAfter a few minutes, the AWS Load Balancer Controller will provision an ALB. You can find its DNS name using
kubectl get ingress laravel-ingress. Update your domain's DNS A record to point to this ALB DNS name.Database and Caching Strategies for Microservices
Managing databases and caches in a microservices architecture requires careful consideration. For Laravel applications on EKS, common patterns involve using managed AWS services like RDS and ElastiCache, or deploying them within Kubernetes itself.
Managed AWS Services (RDS & ElastiCache)
Using RDS for your database and ElastiCache (Redis/Memcached) for caching offers significant operational benefits: scalability, high availability, and reduced management overhead. To connect your Laravel microservices to these services, you'll typically use IAM Roles for Service Accounts (IRSA) to grant pods access to AWS resources securely, rather than embedding credentials.
1. **RDS Setup:** Provision an RDS instance (e.g., MySQL, PostgreSQL). Note its endpoint, port, username, and database name. Store sensitive credentials in Kubernetes Secrets.
apiVersion: v1 kind: Secret metadata: name: auth-service-secrets type: Opaque data: DB_DATABASE: YOUR_BASE64_ENCODED_DB_NAME DB_USERNAME: YOUR_BASE64_ENCODED_DB_USERNAME DB_PASSWORD: YOUR_BASE64_ENCODED_DB_PASSWORD APP_KEY: YOUR_BASE64_ENCODED_APP_KEY2. **ElastiCache Setup:** Provision a Redis or Memcached cluster. Note its endpoint and port.
3. **Network Configuration:** Ensure your EKS worker nodes (in private subnets) can reach the RDS and ElastiCache endpoints. This usually involves configuring Security Groups associated with your RDS/ElastiCache instances to allow inbound traffic from the Security Group of your EKS worker nodes.
Deploying Databases within Kubernetes
For simpler setups or specific requirements, you might deploy databases (e.g., MySQL, PostgreSQL) and caches (e.g., Redis) directly within Kubernetes using StatefulSets and PersistentVolumes. This offers more control but increases operational complexity.
Example
StatefulSetfor Redis:apiVersion: apps/v1 kind: StatefulSet metadata: name: redis spec: selector: matchLabels: app: redis serviceName: "redis" replicas: 1 # Or more for HA, depending on Redis setup template: metadata: labels: app: redis spec: containers: - name: redis image: redis:7.0 ports: - containerPort: 6379 name: redis volumeMounts: - name: redis-data mountPath: /data volumeClaimTemplates: - metadata: name: redis-data spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 10Gi # Adjust storage size as needed storageClassName: gp2 # Or your preferred StorageClass --- apiVersion: v1 kind: Service metadata: name: redis-service spec: selector: app: redis ports: - protocol: TCP port: 6379 targetPort: 6379 clusterIP: None # Headless service for StatefulSetYour Laravel application's configuration would then point to
redis-service.default.svc.cluster.local:6379.Advanced Considerations: CI/CD, Monitoring, and Scaling
Production-ready microservices on EKS demand robust CI/CD pipelines, comprehensive monitoring, and intelligent scaling strategies.
CI/CD Pipeline Integration
Integrate your EKS deployments into your CI/CD workflow. Tools like Jenkins, GitLab CI, GitHub Actions, or AWS CodePipeline can automate the build, test, and deployment process. A typical flow:
- Code commit triggers pipeline.
- Build Docker image.
- Push image to ECR.
- Update Kubernetes manifests (e.g., image tag) using tools like Kustomize or Helm.
- Apply manifests to EKS using
kubectl applyorhelm upgrade.- Consider GitOps approaches with tools like Argo CD or Flux CD for declarative deployments.
Monitoring and Logging
Essential for understanding application health and troubleshooting:
- **Metrics:** Deploy Prometheus and Grafana (often via the Prometheus Operator) to collect metrics from your pods and nodes. Use the Kubernetes Metrics Server for basic resource utilization.
- **Logging:** Implement a centralized logging solution. Options include:
- Fluentd/Fluent Bit as a DaemonSet to collect logs from nodes and forward them to AWS CloudWatch Logs, Elasticsearch, or S3.
- AWS Distro for OpenTelemetry (ADOT) for collecting logs, metrics, and traces.
- **Tracing:** Integrate distributed tracing with tools like Jaeger or AWS X-Ray, especially crucial for understanding request flows across multiple microservices.
Autoscaling
Leverage Kubernetes' autoscaling capabilities:
- **Horizontal Pod Autoscaler (HPA):** Automatically scales the number of pods in a Deployment or StatefulSet based on observed metrics like CPU or memory utilization.
- **Cluster Autoscaler:** Automatically adjusts the number of nodes in your EKS cluster based on pending pods that cannot be scheduled due to resource constraints. Ensure your node groups are configured with appropriate min/max sizes and that the Cluster Autoscaler is installed and configured correctly.
Configuring HPA for a Laravel application pod:
apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: auth-service-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: auth-service-deployment 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: 80 # Scale up when memory utilization reaches 80%This comprehensive approach, from initial cluster setup to advanced operational concerns, provides a solid foundation for running production-grade Laravel microservices on AWS EKS.