Open In App

How To Deploy PHP Application On Kubernetes ?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Prologue to deploying a PHP applications on Kubernetes starts with understanding the containerization, where applications and their libraries are packaged into convenient, lightweight containers. Docker is generally utilized for this reason. Kubernetes then deals with these containers, abstracting away basic infrastructure complexities.

To begin, you’ll require a Kubernetes cluster set up, which includes an master node for orchestration and worker nodes for running containers. Key Kubernetes resources for hosting PHP applications include pods, which outline at least one container, and Deployments, which define the number of replicas of a Unit that ought to be running at some given time.

In this guide we look forward about how to Host a PHP application on kubernetes by declarative manifest method.

What Is Kubernetes?

Kubernetes is a container orchestration platform developed by Google that helps manage and deploy applications run in containers,automating many of manual process involves in deploying,managing,health checking and scaling application. kubernetes also called as k8s because The 8 in K8s represents the number of letters between the “K” and the “s” in the name.

Kubernetes a very powerful automation tool to manage the containerized applications and deploying the containerized applications. Deploying PHP applications on Kubernetes offers a modern and efficient solution for hosting web applications in a scalable and resilient manner. Kubernetes, an open-source container orchestration platform, provides a robust framework for managing containerized workloads, including PHP applications, in a distributed environment. With Kubernetes, PHP developers can leverage features such as automatic scaling, high availability, and rolling updates to ensure seamless deployment and operation of their applications.

we need to understand the concepts of docker,dockerfile,docker images and the containers.By containerizing PHP applications into Docker images and deploying them as pods within Kubernetes clusters, developers can abstract away infrastructure complexities and focus on application development and delivery. Kubernetes enables efficient resource utilization by dynamically scaling PHP application instances based on demand, ensuring optimal performance and cost-effectiveness. Additionally, Kubernetes simplifies service discovery and load balancing, allowing PHP applications to be accessed reliably and securely.

Kubernetes is a two-node cluster one is control plane node(master node)and another one is worker node.

  1. The control plane node hosts the Kubernetes API server and it manages the Kubernetes clusters and resources such as worker nodes and pods.
  2. worker nodes are the part of the cluster that executes applications and containers.

Understanding Of Primary Terminologies

  • kubectl: Kubernetes provides a command line tool for communicating with a Kubernetes cluster’s control plane, using the Kubernetes API.
  • kops: kOps helps us to create,destroy,upgrade and maintain the clusters. With kOps, teams can automate the management of Kubernetes clusters.
  • Primary function: kubernetes is a platform for running and managing containers.
  • Scaling: While a two-node cluster is suitable for testing and development purposes, consider scaling up the cluster as the workload to meet performance. Automatic scaling based on application demand.
  • Networking: Networking configuration is essential to enable communication between nodes and pods within the cluster. Provides complex network setup and supports network policies.
  • Storage: Supports wide range of storage solutions. Persistence,projected and ephemeral volumes.
  • Fault Tolerance: Replaces failed containers automatically
  • Portability: Ensures efficient running of deployed applications in any environment.

What Is PHP?

PHP(short for Hypertext PreProcessor) is the most widely used open source and general purpose server side scripting language used mainly in web development to create dynamic websites and applications.WordPress allows you to host and build websites.It’s widely used for creating dynamic web pages and web applications. PHP code is embedded within HTML documents and executed on the server, generating dynamic content that is then sent to the client’s web browser. With its simple syntax and powerful features, PHP enables developers to interact with databases, handle form data, manage sessions, and perform a wide range of tasks to build dynamic and interactive websites.

WordPress contains plugin architecture and a template system, so you can customize any website to fit your business, blog, portfolio, or online store etc,..It’s supported by a vast community of developers and has extensive documentation, making it accessible for beginners and experienced programmers alike.

Kubernetes Cluster

Deploy PHP Application On Kubernetes : A Step-By-Step Guide

Here, we are going to deploy sample PHP application which is developed by PHP and i host this application in aws EC2 instance.

Step 1 : Create an AWS account and navigate to EC2 and select launch instance.

Launch An Instance With Configuration:

  • AMI- amazon Linux 2
  • instance type- t2.micro
  • Security group- allow SSH(22),HTTP(80),HTTPS(443) traffic from anywhere
  • Configure storage – 8gb with root volume type gp2
  • Connect this instance with any CLI terminal by using SSH
ssh -i  "pemfile" ec2-user@<instance-public-ip address>compute-1.amazonaws.com

EC2 Console

Step 2: Install Docker And Start Docker

  • Install the docker in this instance because we need to create a dockerfile and build the docker image from this dockerfile.
  • Start and enable docker
sudo yum install -y docker
sudo systemctl start docker
sudo systemctl enable docker
Installing Docker

docker installation

  • Start the docker service with the following command:
sudo systemctl start docker
sudo systemctl enable docker
sudo chmod 666 /var/run/docker.sock

Starting the docker service

Step-3:Create PHP Application Files

  • Create a directory for your PHP application.
  • Inside the directory, create an sample index.php file with the following content:
sudo vi index.php
<?php
echo "This is sample PHP application";
?>

Screenshot-2024-03-24-160632

index.php

Step 4: Create Dockerfile

  • In the same directory, create a Dockerfile with the following content:
sudo vi dockerfile
  • Copy the below code to that file named dockerfile:
# Use the official PHP image as base
FROM php:7.4-apache
# Copy PHP files to the container
COPY . /var/www/html/
# Expose port 80 to the outside world
EXPOSE 80

Define Dockerfile

Step 5: Build And Push Docker Image

  • Build your Docker image: docker build -t your-image-name:tag .
docker build -t php:sample

Build And Push Docker Image

  • Tag your Docker image: docker tag your-image-name:tag your-registry/your-image-name:tag
  • Push your Docker image to a container registry: docker push your-registry/your-image-name:tag
  • to push our docker image we need to login into docker hub
docker tag php:sample alaric123/php:sample
docker login
docker push alaric123/php:sample

Building And Pushing The Docker Image

  • Now, list the docker images with the following command:
docker images

Listing the docker images

Step 6: Installing kubectl

  • Download KUBECTL and KOPS related keys and repo from google “https://kops.sigs.k8s.io/getting_started/install/”
  • After downloading the related keys and repos then install kubectl.
sudo yum install -y  kubectl

Installing Kubectl

Step 7: AWS configuration

  • Now,give your aws access key and secret key by the command.
  • here,i use my aws access key and secret key instead of this you can attach ec2 role with admin full access to the ec2 instance.
aws configure

AWS Configuration

Step 8: Make A Amazon S3 bucket

  • Create s3 bucket from this k8 workstation instance to store the objects of the k8s master data.
aws s3 mb  s3://p-h-p

Create an Amazon S3 Bucket

Step 9:Export Amazon S3 Bucket

  • We have to export this s3 bucket for backup and restore the copy files between Kubernetes and S3 bucket.
export KOPS_STATE_STORE=s3://p-h-p

Export Amazon S3 Bucket

Step 10: Generate A SSH Key

  • ssh-keygen command is a component of most SSH implementations used to generate a public key pair for use when authenticating with a remote server
  • We have to generate this ssh-key to create the workers nodes in aws environment.
ssh-keygen

Generate A SSH Key

Step 11: Create k8s Cluster

  • Create a cluster with the DNS “php.k8s.local”
kops create cluster --name php.k8s.local --state s3://p-h-p --zones us-east-1a,us-east-1b --node-count 2 --node-size t2.micro --yes

Creating A Kubernetes Cluster

  • We have to check the cluster whether it is healthy or not and also validation of cluster
kops validate cluster 

Kops Validates Cluster

Now our created cluster is ready ….!!

Step 12: Create A Deployment And Service File

  • The deployment.yml file serves as a configuration file that defines the desired state of the deployment. Create a Deployment to rollout a Replica Set.
  • The Replica Set creates Pods in the background. Check the status of the rollout to see if it succeeds or not.It includes specifications such as the Docker image to use, the number of replicas (instances) of the application to run, resource requirements, environment variables, and other parameters essential for deploying the application.
sudo vi deployment.yml

Copy the below file code to that file name deployment.yml:

  apiVersion: apps/v1
kind: Deployment
metadata:
name: php
spec:
replicas: 2
selector:
matchLabels:
app: php
template:
metadata:
labels:
app: php
spec:
containers:
- name: php-container
image: alaric123/php:sample
ports:
- containerPort: 80

create a service file with yml extension

  • service.yml file is created to define a Kubernetes Service, which is a fundamental resource responsible for providing network access to a set of pods in the cluster. The service.yml file specifies how external clients or other services within the cluster can communicate with the pods that make up an application.
sudo vi service.yml
  • Copy the below file code to the file named service.yml:
apiVersion: v1
kind: Service
metadata:
name: php-service
spec:
selector:
app: php
ports:
- protocol: TCP
port: 80
targetPort: 80

Defining the Service yaml

Step 13: Executing Deployment And Service Yaml Files

  • Execute or apply these deployment.yml and service.yml files with help of kubectl.
  kubectl apply -f deployment.yml
kubectl apply -f service.yml

Executing Deployment and service yaml files

  • After this our replica sets has been created and will ready to run
  • To check the replica sets execute this command
kubectl get all

Listing all the resources

  • So, the desired replica sets are ready

Step 14: Browse EXTERNAL-IP

  • We get the EXTERNAL-IP after applying the deployment.yml and service.yml
  • Copy the given DNS arn of wordpress-service and browse in chrome.
    Browsing the application
  • Finally, our sample php application is successfully deployed and hosted.

PHP Deployment In Kubernetes – FAQ’s

What Are The Prerequisites For Deploying WordPress ( PHP Application ) On Kubernetes?

Ans: Before deploying WordPress on Kubernetes, ensure that you have a Kubernetes cluster set up and configured. make sure you have the access to a container registry to pull Docker images, and any necessary storage solutions for persistent data, such as a Persistent Volume Claim (PVCs) for database storage.

Can I Use Kubernetes To Deploy Non-containerized Applications?

Ans:Kubernetes isn’t a containerization innovation, yet overseeing containerized applications can be utilized.Kubernetes is not a containerization technology, but it can be used to manage containerized applications. primarily designed for containerized workloads, you can use tools like Virtual Kubelet or Kubernetes Operators to deploy and manage non-containerized applications on Kubernetes. However, this approach may require additional configuration and management overhead.

How Does Kubernetes Ensure High Availability And Fault Tolerance?

Kubernetes achieves high availability and fault tolerance through various mechanisms. For example, it automatically restarts failed containers, schedules containers on nodes with available resources, replicates pods across multiple nodes, and supports rolling updates to minimize downtime during deployments.

Can I Scale My Php Application Horizontally In Kubernetes?

Ans: Kubernetes gives different scaling mechanisms. you can physically scale an Organization unit by changing the reproductions design.For example, you can manually scale a Deployment unit by adjusting the replicas configuration. Additionally, Kubernetes offers Horizontal Pod Autoscaling (HPA), which automatically scales the number of pods based on CPU or custom metrics.

What Is Kubernetes (k8s), And Why Would I Use It To Deploy My Php Application?

A: Kubernetes is a container orchestration management platform that automates the deployment, scaling, and management of containerized applications. Deploying PHP applications in Kubernetes provides benefits such as scalability, reliability, and efficient ,volumes resource utilization.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads