Deploying PHP on Kubernetes: A Basic Guide
Modern web development increasingly requires scalable and fault-tolerant solutions. Kubernetes (K8s) has become the de facto standard for container orchestration. If you are a PHP developer and want to learn how to deploy your applications to Kubernetes, this guide is for you. We will go from creating a Docker image to deploying a full-fledged PHP service in a cluster.
Why Deploy PHP on Kubernetes?
Kubernetes provides several advantages for PHP applications:
- Automatic Scaling: K8s can increase the number of pods when load increases and decrease it when load drops.
- Self-Healing: If a container fails, Kubernetes automatically restarts it.
- Configuration Management: Environment variables and configuration files can be easily centralized using ConfigMap and Secrets.
- Simplified Updates: Rolling updates allow you to update the application without downtime.
This is especially relevant for PHP, as many legacy projects are difficult to scale using traditional methods.
Step 1: Containerizing the PHP Application
Before deploying an application to Kubernetes, it needs to be packaged into a Docker image. Let's look at an example of a simple PHP application using Nginx and PHP-FPM.
Creating the Project Structure
my-php-app/├── src/│ └── index.php├── docker/│ ├── nginx/│ │ └── default.conf│ └── php/│ └── Dockerfile└── docker-compose.ymlExample src/index.php
<?phpecho "Hello from PHP on Kubernetes!";phpinfo();?>Dockerfile for PHP-FPM
FROM php:8.2-fpm-alpine
RUN docker-php-ext-install pdo pdo_mysql
COPY src/ /var/www/html/
EXPOSE 9000CMD ["php-fpm"]Nginx Configuration (docker/nginx/default.conf)
server { listen 80; server_name localhost; root /var/www/html;
location / { try_files $uri $uri/ /index.php?$query_string; }
location ~ \\.php$ { fastcgi_pass php:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }}Building the Image
docker build -t my-php-app:latest -f docker/php/Dockerfile .Step 2: Writing Kubernetes Manifests
Now that the image is ready, let's create manifests for deployment in the cluster.
Deployment for PHP-FPM
apiVersion: apps/v1kind: Deploymentmetadata: name: php-app labels: app: php-appspec: replicas: 3 selector: matchLabels: app: php-app template: metadata: labels: app: php-app spec: containers: - name: php-fpm image: my-php-app:latest ports: - containerPort: 9000 env: - name: DB_HOST value: "mysql-service" - name: DB_NAME value: "mydb" resources: requests: memory: "128Mi" cpu: "250m" limits: memory: "256Mi" cpu: "500m"Deployment for Nginx
apiVersion: apps/v1kind: Deploymentmetadata: name: nginx labels: app: nginxspec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:alpine ports: - containerPort: 80 volumeMounts: - name: nginx-config mountPath: /etc/nginx/conf.d volumes: - name: nginx-config configMap: name: nginx-config