Deploying and Scaling a Kubernetes Web Application
In this section, we'll explore the process of deploying and scaling a web application on a Kubernetes cluster. We'll cover the key concepts and demonstrate how to set up a scalable and highly available web application.
Deploying a Web Application
To deploy a web application on Kubernetes, we'll use a Deployment object. Here's an example of a Deployment YAML file for a simple web application:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: web-app
image: username/web-app:v1
ports:
- containerPort: 8080
This Deployment creates three replicas of the web-app
container, which exposes port 8080. The Pods created by this Deployment will have the label app=web-app
.
To expose the web application to the outside world, we'll create a Service:
apiVersion: v1
kind: Service
metadata:
name: web-app-service
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 8080
selector:
app: web-app
This Service of type LoadBalancer
will create a load balancer in your cloud provider and forward traffic from port 80 to the target port 8080 of the Pods with the app=web-app
label.
Scaling the Web Application
One of the key benefits of Kubernetes is its ability to automatically scale your application based on demand. You can scale your application by updating the replicas
field in the Deployment specification:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 5
## ... other Deployment configuration
Kubernetes will then create two additional Pods to meet the new desired state of five replicas.
Persistent Storage
To ensure that your web application can persist data, you can use Kubernetes Volumes. Here's an example of a Deployment that uses a persistent volume claim (PVC) to mount a volume to the web application container:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: web-app
image: username/web-app:v1
ports:
- containerPort: 8080
volumeMounts:
- name: data
mountPath: /app/data
volumes:
- name: data
persistentVolumeClaim:
claimName: web-app-data
In this example, the web application container mounts a volume named data
to the /app/data
directory. The volume is backed by a persistent volume claim (PVC) named web-app-data
.