Deploying Nginx Web Server on a Kubernetes Cluster
Using the imperative approach, we will deploy a highly available Nginx web server on a Kubernetes cluster. We'll achieve this by creating a Deployment and a Service object using a YAML manifest file. We will save the output of the below command and add a service object later.
kubectl create deployment nginx-deployment --image:nginx:latest --replicas=3 -o yaml
Understanding the Components:
Deployment: A Deployment object manages the lifecycle of multiple Nginx pod replicas. It ensures that the desired number of pods are running and automatically scales or updates them based on defined configurations.
Service: A Service acts as a virtual IP and port abstraction for the Deployment. It provides a stable way to access the Nginx pods, even if their IP addresses change. This allows external clients to connect to the service using a consistent address.
apiVersion: apps/v1
kind: Deployment
metadata:
spec:
replicas: 3
selector:
matchLabels:
app: nginx-deployment
template:
metadata:
labels:
app: nginx-deployment
spec:
containers:
- image: nginx:latest
name: nginx-container
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
type: NodePort
selector:
app: nginx-deployment
ports:
- port: 80
targetPort: 80
nodePort: 30011
Explanation:
The Deployment section:
Defines the number of replicas (3 in this case) for the Nginx container.
Uses label selectors to identify pods belonging to this deployment.
The template specifies the container image (nginx:latest) and its name.
The Service section:
The type is set to NodePort, exposing the service to a randomly allocated node port (30011 in this example).
The selector matches the labels defined in the Deployment, ensuring the service exposes the correct pods.
Recommended by LinkedIn
Maps container port 80 (default Nginx port) to the service port 80 and node port 30011.
Deploying the Nginx Service:
Save the manifest as a YAML file (e.g., nginx-deployment.yaml).
Run the following command to create the Deployment and Service:
kubectl create -f nginx-deployment.yaml
Accessing the Nginx Service:
Once the deployment is complete, you can access the Nginx web server from any node in the cluster using the allocated node port:
<Node_IP_Address>:30011
Replace <Node_IP_Address> with the IP address of any worker node in your Kubernetes cluster.
This will connect you to the Nginx web server running on any of the deployed pods, demonstrating the service's ability to distribute traffic across replicas.