Orchestrating Microservices with Kubernetes: A Deep Dive into PHP 8.x and Laravel on AWS EKS
Setting Up AWS EKS for PHP Microservices
Deploying PHP 8.x applications, particularly those built with Laravel, on Kubernetes requires a robust and well-configured cluster. AWS Elastic Kubernetes Service (EKS) provides a managed Kubernetes experience, abstracting away much of the control plane complexity. Our focus here is on a production-ready setup, emphasizing security, scalability, and observability.
The initial step involves provisioning an EKS cluster. We’ll use `eksctl`, the official CLI for EKS, to define our cluster configuration. This approach ensures reproducibility and allows for fine-grained control over cluster settings.
Cluster Configuration with `eksctl`
Create a file named cluster.yaml with the following content. This configuration defines a cluster with a managed node group, suitable for most production workloads. We’ll specify a Kubernetes version, region, and instance types for our worker nodes. Enabling IAM OIDC provider is crucial for integrating AWS services with Kubernetes pods.
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
name: php-microservices-cluster
region: us-east-1
version: "1.28" # Specify your desired Kubernetes version
iam:
withOIDC: true
nodeGroups:
- name: default-workers
instanceType: m5.large # Choose an appropriate instance type
desiredCapacity: 3
minSize: 1
maxSize: 5
volumeSize: 80 # GiB
ssh:
allow: false # For production, disable direct SSH access
privateNetworking: true # Recommended for security
tags:
nodegroup-role: worker
environment: production
Once the configuration file is ready, deploy the cluster using the following command:
eksctl create cluster -f cluster.yaml
This process can take 15-20 minutes. After successful creation, `eksctl` will automatically update your ~/.kube/config file to point to the new cluster.
Ingress Controller: Nginx on EKS
To expose our PHP microservices to the internet, we need an Ingress controller. The Nginx Ingress Controller is a popular and robust choice. We’ll deploy it using Helm, the Kubernetes package manager.
First, add the Nginx Ingress Helm repository:
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx helm repo update
Next, install the Nginx Ingress Controller. We’ll configure it to use an AWS Application Load Balancer (ALB) for external traffic. This involves setting the `controller.service.annotations` to provision an ALB. The `kubernetes.io/ingress.class: nginx` annotation is crucial for directing Ingress resources to this controller.
helm install ingress-nginx ingress-nginx/ingress-nginx \
--namespace ingress-nginx \
--create-namespace \
--set controller.replicaCount=2 \
--set controller.nodeSelector."kubernetes\.io/os"=linux \
--set controller.admissionWebhooks.patch.nodeSelector."kubernetes\.io/os"=linux \
--set controller.service.annotations."kubernetes\.io/ingress.class"="nginx" \
--set controller.service.annotations."alb.ingress.kubernetes.io/scheme"="internet-facing" \
--set controller.service.annotations."alb.ingress.kubernetes.io/target-type"="ip" \
--set controller.service.annotations."alb.ingress.kubernetes.io/listen-ports"='[{"HTTP": 80}, {"HTTPS":443}]' \
--set controller.service.annotations."alb.ingress.kubernetes.io/ssl-redirect"="true" \
--set controller.service.annotations."cert-manager.io/cluster-issuer"="letsencrypt-prod"
The `cert-manager.io/cluster-issuer` annotation assumes you have cert-manager installed and configured for automatic TLS certificate provisioning with Let’s Encrypt. If not, you’ll need to manage TLS certificates manually or configure cert-manager separately.
Deploying a Laravel Microservice
Let’s consider a simple Laravel microservice that exposes an API endpoint. We’ll need a Dockerfile to containerize the application.
# Use an official PHP runtime as a parent image
FROM php:8.2-fpm
# Set the working directory in the container
WORKDIR /var/www/html
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
unzip \
libzip-dev \
libpng-dev \
libjpeg-dev \
libfreetype6-dev \
nginx \
procps \
cron \
supervisor \
&& rm -rf /var/lib/apt/lists/*
# Install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd zip pdo pdo_mysql \
&& pecl install redis \
&& docker-php-ext-enable redis
# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Copy the application code
COPY . .
# Install dependencies
RUN composer install --no-dev --optimize-autoloader
# Configure Nginx
COPY docker/nginx.conf /etc/nginx/sites-available/default
RUN ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default
# Configure Supervisor for PHP-FPM and Queue Workers
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
# Expose port 8000 (Nginx default)
EXPOSE 8000
# Start services
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
You’ll also need a basic docker/nginx.conf and docker/supervisord.conf. The Nginx config should point to the PHP-FPM socket, and the supervisor config should manage both php-fpm and your Laravel queue worker.
Kubernetes Manifests for Deployment
We’ll define Kubernetes resources using YAML manifests. This includes a Deployment for our Laravel application, a Service to expose it internally within the cluster, and an Ingress resource to route external traffic to the service.
First, the Deployment manifest:
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-api-deployment
labels:
app: laravel-api
spec:
replicas: 3 # Adjust based on your needs
selector:
matchLabels:
app: laravel-api
template:
metadata:
labels:
app: laravel-api
spec:
containers:
- name: laravel-api
image: YOUR_ECR_REPO/laravel-api:latest # Replace with your ECR image
ports:
- containerPort: 8000
env:
- name: APP_ENV
value: "production"
- name: APP_KEY
valueFrom:
secretKeyRef:
name: laravel-secrets
key: APP_KEY
- name: DB_HOST
value: "mysql-service.default.svc.cluster.local" # Example for internal DB service
- name: DB_PORT
value: "3306"
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: laravel-secrets
key: DB_DATABASE
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-secrets
key: DB_USERNAME
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-secrets
key: DB_PASSWORD
readinessProbe:
httpGet:
path: /healthz # Assuming you have a health check endpoint
port: 8000
initialDelaySeconds: 15
periodSeconds: 10
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 30
periodSeconds: 20
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "512Mi"
imagePullSecrets:
- name: aws-ecr-credentials # If using private ECR
Next, the Service manifest. This provides a stable internal IP address and DNS name for our application pods.
apiVersion: v1
kind: Service
metadata:
name: laravel-api-service
spec:
selector:
app: laravel-api
ports:
- protocol: TCP
port: 80
targetPort: 8000 # The port Nginx inside the container listens on
Finally, the Ingress manifest. This tells the Nginx Ingress Controller how to route external traffic to our laravel-api-service. The annotations are key for integrating with AWS ALB and cert-manager.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: laravel-api-ingress
annotations:
kubernetes.io/ingress.class: "nginx"
alb.ingress.kubernetes.io/scheme: "internet-facing"
alb.ingress.kubernetes.io/target-type: "ip"
alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS":443}]'
alb.ingress.kubernetes.io/ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod" # Ensure this issuer exists
spec:
tls:
- hosts:
- api.yourdomain.com # Replace with your domain
secretName: laravel-api-tls-secret # Cert-manager will create this
rules:
- host: api.yourdomain.com # Replace with your domain
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: laravel-api-service
port:
number: 80
To apply these manifests, save them to files (e.g., deployment.yaml, service.yaml, ingress.yaml) and run:
kubectl apply -f deployment.yaml kubectl apply -f service.yaml kubectl apply -f ingress.yaml
Database and Secrets Management
For production, it’s highly recommended to use AWS RDS for your database. You’ll need to provision an RDS instance and configure its security group to allow inbound traffic from your EKS worker nodes’ CIDR range. The database connection details (username, password, database name) should be stored as Kubernetes Secrets.
Create a Kubernetes secret for your Laravel application’s sensitive environment variables:
kubectl create secret generic laravel-secrets \ --from-literal=APP_KEY='base64:YOUR_APP_KEY_HERE' \ --from-literal=DB_DATABASE='your_db_name' \ --from-literal=DB_USERNAME='your_db_user' \ --from-literal=DB_PASSWORD='your_db_password'
Replace YOUR_APP_KEY_HERE with your actual Laravel application key (base64 encoded). Ensure the database credentials match your RDS instance.
CI/CD Pipeline with AWS CodePipeline and ECR
A robust CI/CD pipeline is essential for microservices. We’ll outline a basic flow using AWS CodePipeline, CodeBuild, and ECR.
- Source Stage: Triggered by commits to your Git repository (e.g., CodeCommit, GitHub).
- Build Stage (CodeBuild):
- Fetches the source code.
- Builds the Docker image using the
Dockerfile. - Tags the image with a unique identifier (e.g., commit hash or build ID).
- Pushes the image to AWS Elastic Container Registry (ECR).
- (Optional) Updates Kubernetes manifests with the new image tag.
- Deploy Stage (Manual or Automated):
- Applies the updated Kubernetes manifests to your EKS cluster. This can be done via a CodeBuild project that runs
kubectl applyor by using a dedicated deployment tool like Argo CD or Flux.
- Applies the updated Kubernetes manifests to your EKS cluster. This can be done via a CodeBuild project that runs
For the build stage in CodeBuild, your buildspec.yml might look like this:
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to Amazon ECR...
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
- REPOSITORY_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME
- COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c1-7)
- IMAGE_TAG=$COMMIT_HASH
build:
commands:
- echo Build started on `date`
- echo Building the Docker image...
- docker build -t $REPOSITORY_URI:latest -t $REPOSITORY_URI:$IMAGE_TAG .
post_build:
commands:
- echo Pushing the Docker image...
- docker push $REPOSITORY_URI:latest
- docker push $REPOSITORY_URI:$IMAGE_TAG
- echo Writing image definitions file...
- printf '{"ImageRepository":"%s","ImageTag":"%s"}' $REPOSITORY_URI $IMAGE_TAG > imageDetail.json
# Optional: Update Kubernetes deployment with new image tag
# - sed -i "s|image: YOUR_ECR_REPO/laravel-api:latest|image: $REPOSITORY_URI:$IMAGE_TAG|g" kubernetes/deployment.yaml
# - kubectl apply -f kubernetes/deployment.yaml
Ensure that the CodeBuild service role has permissions to push to ECR and potentially to interact with EKS (if automating deployments directly from CodeBuild).
Monitoring and Logging
For production environments, robust monitoring and logging are non-negotiable. Consider integrating:
- Prometheus and Grafana: For collecting and visualizing metrics from your applications and Kubernetes cluster.
- Fluentd/Fluent Bit: As a log collector to aggregate logs from all pods and forward them to a centralized logging solution like AWS CloudWatch Logs, Elasticsearch, or Loki.
- AWS CloudWatch Container Insights: Provides enhanced monitoring for containerized applications on EKS.
Configuring these often involves deploying additional Helm charts or Kubernetes operators. For instance, deploying the Prometheus community Helm chart and then configuring scraping for your application pods is a common pattern.
Conclusion
Orchestrating PHP 8.x and Laravel microservices on AWS EKS involves careful configuration of the Kubernetes cluster, ingress, deployments, and CI/CD pipelines. By leveraging managed services like EKS and integrating with AWS’s ecosystem (ECR, RDS, CodePipeline), you can build scalable, resilient, and observable microservice architectures. Remember to adapt resource requests/limits, replica counts, and security configurations based on your specific application’s performance characteristics and your organization’s security policies.