Beyond Basic Orchestration: Implementing GitOps with Argo CD for Autonomous PHP/Laravel Deployments on Kubernetes
Setting the Stage: Kubernetes, Argo CD, and GitOps Fundamentals
This post dives deep into implementing a robust GitOps workflow for PHP/Laravel applications on Kubernetes, leveraging Argo CD for autonomous deployments. We’ll move beyond basic orchestration to a declarative, auditable, and self-healing system. The core principle of GitOps is that Git is the single source of truth for both application code and infrastructure configuration. Changes to the desired state are made via Git commits, and automated tooling ensures the live environment matches this state.
Our target environment is Kubernetes. For GitOps tooling, we’ll focus on Argo CD, a declarative, GitOps continuous delivery tool for Kubernetes. It synchronizes the desired state specified in a Git repository with the live Kubernetes cluster state.
Prerequisites and Initial Setup
Before we begin, ensure you have:
- A running Kubernetes cluster (e.g., GKE, EKS, AKS, or a local setup like Minikube/Kind).
kubectlconfigured to interact with your cluster.- A Git repository (e.g., GitHub, GitLab, Bitbucket) to host your application code and Kubernetes manifests.
- Docker installed for building container images.
First, install Argo CD into your Kubernetes cluster. We’ll use the default namespace for simplicity, but in production, consider a dedicated namespace like argocd.
Installing Argo CD
Apply the Argo CD installation manifest:
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 development or testing, port-forwarding is convenient. In production, you’d typically set up an Ingress or LoadBalancer.
Accessing the Argo CD UI
Get the initial admin password:
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d; echo
Port-forward the Argo CD API server:
kubectl port-forward svc/argocd-server -n argocd 8080:443
Now, access the Argo CD UI at https://localhost:8080 (you’ll need to bypass the self-signed certificate warning). Log in with username admin and the password obtained previously.
Structuring Your Git Repository for GitOps
A well-structured Git repository is crucial. We’ll adopt a monorepo approach where both application code and its Kubernetes manifests reside. This simplifies dependency management and ensures consistency.
Monorepo Structure Example
Consider the following directory structure:
/my-laravel-app ├── app/ ├── bootstrap/ ├── config/ ├── database/ ├── public/ ├── resources/ ├── routes/ ├── storage/ ├── tests/ ├── vendor/ ├── artisan ├── composer.json ├── .env.example ├── Dockerfile ├── kubernetes/ │ ├── base/ │ │ ├── deployment.yaml │ │ ├── service.yaml │ │ └── ingress.yaml (optional) │ └── overlays/ │ ├── development/ │ │ ├── kustomization.yaml │ │ └── deployment-patch.yaml │ └── production/ │ ├── kustomization.yaml │ └── deployment-patch.yaml ├── .gitignore └── README.md
In this structure:
- The root contains your Laravel application files.
Dockerfiledefines how to build your application’s container image.kubernetes/basecontains the fundamental Kubernetes manifests that apply to all environments.kubernetes/overlaysuses Kustomize to manage environment-specific configurations. This is a powerful pattern for GitOps, allowing you to define base configurations and then apply patches for different environments (e.g., development, staging, production).
Containerizing Your Laravel Application
A robust Dockerfile is essential for reproducible builds. We’ll use a multi-stage build to keep the final image lean.
Example Dockerfile
# Stage 1: Build dependencies
FROM composer:latest as composer_deps
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader --no-scripts
# Stage 2: Build application
FROM php:8.2-fpm as app_builder
WORKDIR /app
COPY --from=composer_deps /app/vendor ./vendor
COPY . .
RUN php artisan optimize:clear \
&& php artisan config:cache \
&& php artisan route:cache \
&& php artisan view:cache \
&& chown -R www-data:www-data storage bootstrap/cache \
&& chmod -R 775 storage bootstrap/cache
# Stage 3: Production image
FROM php:8.2-fpm-alpine
WORKDIR /app
COPY --from=app_builder /app .
# Install necessary PHP extensions for production (e.g., pdo_mysql, redis)
RUN apk add --no-cache \
libzip-dev \
zip \
libpng-dev \
libjpeg-turbo-dev \
freetype-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd pdo_mysql \
&& apk del libzip-dev libpng-dev libjpeg-turbo-dev freetype-dev
# Copy application code
COPY --from=app_builder /app .
# Expose port and set user
EXPOSE 9000
USER www-data
# Default command to run PHP-FPM
CMD ["php-fpm"]
This Dockerfile:
- Uses
composer:latestto install dependencies. - Builds the application, caching configuration, routes, and views.
- Creates a lean production image using
php:8.2-fpm-alpine. - Installs essential extensions like GD, PDO MySQL.
- Sets the correct user and exposes the PHP-FPM port.
You’ll need a container registry (e.g., Docker Hub, GCR, ECR) to push your images. A CI/CD pipeline (e.g., GitHub Actions, GitLab CI) will handle building and pushing these images on code commits.
Defining Kubernetes Manifests with Kustomize
Kustomize is a template-free way to customize Kubernetes configurations. Argo CD has first-class support for Kustomize.
Base Manifests (kubernetes/base/)
These are the common configurations for your application.
Deployment Manifest (deployment.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-laravel-app
labels:
app: my-laravel-app
spec:
replicas: 1 # This will be managed by Kustomize overlays
selector:
matchLabels:
app: my-laravel-app
template:
metadata:
labels:
app: my-laravel-app
spec:
containers:
- name: app
image: your-docker-registry/my-laravel-app:latest # Placeholder, will be overridden
ports:
- containerPort: 9000
env:
- name: APP_ENV
value: "production"
- name: APP_URL
value: "http://localhost" # Placeholder, will be overridden
- name: APP_KEY
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: APP_KEY
- name: DB_HOST
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_HOST
- name: DB_PORT
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_PORT
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_DATABASE
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_USERNAME
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_PASSWORD
volumeMounts:
- name: storage
mountPath: /app/storage
- name: bootstrap-cache
mountPath: /app/bootstrap/cache
volumes:
- name: storage
emptyDir: {} # Will be replaced by PersistentVolumeClaim in overlays
- name: bootstrap-cache
emptyDir: {} # Will be replaced by PersistentVolumeClaim in overlays
Service Manifest (service.yaml)
apiVersion: v1
kind: Service
metadata:
name: my-laravel-app-service
spec:
selector:
app: my-laravel-app
ports:
- protocol: TCP
port: 80
targetPort: 9000 # PHP-FPM port
Environment-Specific Overlays (kubernetes/overlays/)
Each environment directory will contain a kustomization.yaml file and any necessary patches.
Development Overlay (kubernetes/overlays/development/)
apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../base namespace: development images: - name: your-docker-registry/my-laravel-app newTag: dev-$(GIT_COMMIT_SHA) # Example: dynamically set image tag patchesStrategicMerge: - deployment-patch.yaml configMapGenerator: - name: laravel-app-config literals: - APP_ENV=development - APP_URL=http://dev.myapp.com - DB_HOST=mysql-dev - DB_PORT=3306 - DB_DATABASE=myapp_dev - DB_USERNAME=user_dev - DB_PASSWORD=password_dev # Sensitive data should be in Secrets, not ConfigMaps secretGenerator: - name: laravel-app-secrets literals: - APP_KEY=base64:your_base64_encoded_app_key - DB_HOST=mysql-dev - DB_PORT=3306 - DB_DATABASE=myapp_dev - DB_USERNAME=user_dev - DB_PASSWORD=password_dev
Note: Storing secrets directly in secretGenerator is for demonstration. In production, use external secret management solutions like HashiCorp Vault or Kubernetes Secrets managed via a separate, more secure GitOps workflow.
Deployment Patch (deployment-patch.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-laravel-app # Must match the name in the base deployment
spec:
replicas: 2
template:
spec:
containers:
- name: app
image: your-docker-registry/my-laravel-app:dev-$(GIT_COMMIT_SHA) # Override image tag
env:
- name: APP_URL
value: "http://dev.myapp.com" # Override APP_URL
volumeMounts:
- name: storage
mountPath: /app/storage
- name: bootstrap-cache
mountPath: /app/bootstrap/cache
volumes:
- name: storage
persistentVolumeClaim:
claimName: laravel-storage-pvc
- name: bootstrap-cache
persistentVolumeClaim:
claimName: laravel-bootstrap-cache-pvc
The kustomization.yaml in the development overlay:
- References the base manifests.
- Sets the target namespace to
development. - Overrides the container image tag, potentially using an environment variable like
GIT_COMMIT_SHApassed during CI. - Applies a strategic merge patch to the deployment for environment-specific settings like replica count and volume mounts.
- Uses
configMapGeneratorandsecretGeneratorto inject environment-specific configuration and secrets.
Configuring Argo CD Applications
Now, we’ll tell Argo CD to monitor our Git repository and deploy the Kustomize configurations to our Kubernetes cluster.
Creating an Argo CD Application
You can do this via the Argo CD UI or by creating an Argo CD Application custom resource. Using a custom resource is the GitOps way!
Argo CD Application Manifest (argocd-app.yaml)
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: my-laravel-app-dev
namespace: argocd # Argo CD's namespace
spec:
project: default # Or a specific Argo CD project
source:
repoURL: https://github.com/your-username/my-laravel-app.git # Your Git repo URL
targetRevision: HEAD # Or a specific branch like 'main'
path: kubernetes/overlays/development # Path to Kustomize overlay
kustomize:
# Optional: If your kustomize needs specific build arguments
# buildOptions: "--enable-helm"
destination:
server: https://kubernetes.default.svc # Target Kubernetes cluster
namespace: development # Target namespace in Kubernetes
syncPolicy:
automated:
prune: true # Automatically delete resources that are no longer defined
selfHeal: true # Automatically sync if the live state drifts from Git
syncOptions:
- CreateNamespace=true # Automatically create the namespace if it doesn't exist
Apply this manifest to your cluster:
kubectl apply -f argocd-app.yaml
Navigate to the Argo CD UI. You should see your application listed. Argo CD will now:
- Clone your Git repository.
- Navigate to the specified path (
kubernetes/overlays/development). - Run
kustomize buildon that path. - Compare the generated Kubernetes manifests with the live state in the
developmentnamespace of your cluster. - If there are differences and
syncPolicy.automatedis enabled, it will automatically apply the changes to reconcile the cluster state with Git.
Handling Database Migrations and Other Laravel Tasks
Autonomous deployments mean handling tasks like database migrations, seeding, and cache clearing without manual intervention. This is a common challenge with GitOps and stateful applications.
Option 1: Kubernetes Jobs for Migrations
You can define a Kubernetes Job that runs your migrations. This job would be triggered as part of the deployment process.
Migration Job Manifest (kubernetes/overlays/development/migration-job.yaml)
apiVersion: batch/v1
kind: Job
metadata:
name: my-laravel-app-migrations
annotations:
"argocd.argoproj.io/hook": PostSync # Run after the main application sync
"argocd.argoproj.io/hook/skip-on-error": "true"
spec:
template:
spec:
containers:
- name: migration
image: your-docker-registry/my-laravel-app:dev-$(GIT_COMMIT_SHA) # Use the same image as the app
command: ["php", "artisan", "migrate", "--force"] # --force is crucial for production
envFrom:
- configMapRef:
name: laravel-app-config
env:
- name: APP_KEY
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: APP_KEY
- name: DB_HOST
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_HOST
- name: DB_PORT
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_PORT
- name: DB_DATABASE
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_DATABASE
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_USERNAME
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: laravel-app-secrets
key: DB_PASSWORD
restartPolicy: Never # Jobs should not restart on failure, they complete or fail
Add this job to your kubernetes/overlays/development/kustomization.yaml:
apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../base - migration-job.yaml # Add the job here namespace: development images: - name: your-docker-registry/my-laravel-app newTag: dev-$(GIT_COMMIT_SHA) patchesStrategicMerge: - deployment-patch.yaml configMapGenerator: # ... (previous configMapGenerator) secretGenerator: # ... (previous secretGenerator)
The argocd.argoproj.io/hook: PostSync annotation tells Argo CD to run this job *after* the main deployment has been successfully synchronized. The --force flag is essential for migrations to ensure they run even if the application deployment was rolled back and then re-deployed.
Option 2: Entrypoint Script with Migration Check
Alternatively, you can modify your application’s entrypoint to check for and run migrations when the container starts. This is simpler but can lead to race conditions if multiple pods start simultaneously.
Modified Dockerfile (Entrypoint)
# ... (previous stages)
# Stage 3: Production image
FROM php:8.2-fpm-alpine
WORKDIR /app
# Copy application code
COPY --from=app_builder /app .
# Install necessary PHP extensions
RUN apk add --no-cache \
libzip-dev \
zip \
libpng-dev \
libjpeg-turbo-dev \
freetype-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd pdo_mysql \
&& apk del libzip-dev libpng-dev libjpeg-turbo-dev freetype-dev
# Copy custom entrypoint script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
EXPOSE 9000
USER www-data
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["php-fpm"]
Custom Entrypoint Script (docker-entrypoint.sh)
#!/bin/sh
# Check if running in a non-production environment or if migrations are explicitly enabled
if [ "$APP_ENV" != "production" ] || [ "$RUN_MIGRATIONS" = "true" ]; then
echo "Running database migrations..."
php artisan migrate --force
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
fi
# Execute the CMD
exec "$@"
To enable this, you would set the RUN_MIGRATIONS environment variable to true in your Kustomize overlay for non-production environments, or rely on the APP_ENV check for development. For production, it’s generally safer to use Kubernetes Jobs.
Advanced Considerations and Best Practices
Secrets Management
Never commit plain-text secrets to Git. Use external secret management tools like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault, and integrate them with Kubernetes. Argo CD can sync these secrets into your cluster.
Image Tagging Strategy
Avoid using latest for production images. Implement a strategy that uses Git commit SHAs, semantic versioning, or build timestamps for immutable image tags. This ensures that deployments are always tied to a specific, known artifact.
Health Checks and Readiness Probes
Implement robust livenessProbe and readinessProbe in your Kubernetes Deployment manifests. For Laravel, a simple HTTP check on a dedicated health endpoint (e.g., /health) that checks database connectivity and application status is recommended.
Rollback Strategies
Argo CD supports automatic rollbacks if a sync fails. For manual rollbacks, simply revert the commit in your Git repository that introduced the problematic change. Argo CD will detect the drift and revert the cluster state.
Multi-Cluster and Multi-Environment Deployments
Argo CD excels at managing deployments across multiple Kubernetes clusters and environments. You can define different Argo CD Application resources, each pointing to a specific Git path (e.g., kubernetes/overlays/staging, kubernetes/overlays/production) and a different cluster or namespace.
Conclusion
By adopting GitOps with Argo CD for your PHP/Laravel applications on Kubernetes, you establish a declarative, auditable, and automated deployment pipeline. This approach significantly reduces manual errors, improves deployment speed, and provides a clear audit trail for all changes. Remember to tailor the secrets management and migration strategies to your specific production requirements for maximum security and reliability.