Kubernetes Services ( ClusterIP, LoadBalancer and NodePort ) example using Nginx

To understand the Kubernetes services, lets create a simple image, that you can use to understand and experiment with ClusterIP, LoadBalancer, and NodePort services in Kubernetes. For simplicity, let’s assume a basic web server scenario.

  1. Create a Docker Image for a Simple Web Server:  Create a file named Dockerfile with the following content:
    Create an index.html file in the same directory with some content.

FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.html

Build the Docker image:

docker build -t simple-web-server .

2. Deployment YAML:

Create a Deployment YAML file (deployment.yaml):

package main
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: example-app
  template:
    metadata:
      labels:
        app: example-app
    spec:
      containers:
      - name: web-server
        image: simple-web-server

Apply the deployment:

kubectl apply -f deployment.yaml

Service YAML for ClusterIP (service-clusterip.yaml):

package main
apiVersion: v1
kind: Service
metadata:
  name: example-service-clusterip
spec:
  selector:
    app: example-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: ClusterIP

Apply the ClusterIP service:

kubectl apply -f service-clusterip.yaml

Service YAML for NodePort (service-nodeport.yaml):

package main
apiVersion: apps/v1
apiVersion: v1
kind: Service
metadata:
  name: example-service-nodeport
spec:
  selector:
    app: example-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: NodePort

Apply the NodePort service:

kubectl apply -f service-nodeport.yaml

Service YAML for LoadBalancer (service-loadbalancer.yaml):

package main
apiVersion: v1
kind: Service
metadata:
  name: example-service-loadbalancer
spec:
  selector:
    app: example-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: LoadBalancer

Apply the LoadBalancer service:

kubectl apply -f service-loadbalancer.yaml

Now, you have a simple web server deployed in Kubernetes with different service types (ClusterIP, NodePort, and LoadBalancer). You can access them based on the service type and experiment with the behavior.

Leave a Reply

Your email address will not be published. Required fields are marked *