Deploying a Web Application on Kubernetes
Now that we have a basic understanding of Kubernetes, let's dive deeper and learn how to deploy a more complex web application on a Kubernetes cluster. In this section, we'll cover the key Kubernetes concepts and resources needed to deploy and manage a web application, including Pods, Services, and Volumes.
Pods and Containers
In Kubernetes, the fundamental unit of deployment is a Pod, which represents one or more containers running together. Containers within a Pod share the same network namespace and can communicate with each other using localhost
. This makes it easy to create multi-container applications, where each container specializes in a specific task, such as a web server, a database, or a message queue.
Here's an example of a Pod manifest that runs a web server and a database container:
apiVersion: v1
kind: Pod
metadata:
name: my-web-app
spec:
containers:
- name: web-server
image: nginx:latest
ports:
- containerPort: 80
- name: database
image: mysql:5.7
env:
- name: MYSQL_ROOT_PASSWORD
value: mypassword
Services and Load Balancing
While Pods provide the basic building blocks for your application, you'll typically want to expose your web application to the outside world using a Kubernetes Service. A Service is an abstraction that defines a logical set of Pods and a policy by which to access them.
Here's an example of a Service manifest that exposes the web server Pod from the previous example:
apiVersion: v1
kind: Service
metadata:
name: my-web-app-service
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 80
selector:
app: my-web-app
This Service manifest creates a LoadBalancer type service that will expose the web server Pod on port 80. The selector
field matches the Pods with the app=my-web-app
label.
Volumes and Persistent Storage
In addition to the web application itself, you'll often need to persist data, such as user uploads, configuration files, or database data. Kubernetes provides a powerful abstraction called Volumes, which allow you to attach storage to your Pods.
Here's an example of a Pod manifest that uses a Volume to store database data:
apiVersion: v1
kind: Pod
metadata:
name: my-database
spec:
containers:
- name: database
image: mysql:5.7
env:
- name: MYSQL_ROOT_PASSWORD
value: mypassword
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumes:
- name: data
emptyDir: {}
In this example, the emptyDir
volume type is used to create a temporary storage volume that persists for the lifetime of the Pod. You can also use other volume types, such as hostPath
or persistentVolumeClaim
, to provide more durable storage solutions.