Kubernetes Services ( ClusterIP, LoadBalancer and NodePort ) example using Node.js

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 create a simple Node.js web server for this purpose..

  1. Create a Node.js web server::
    Create a file named server.js with the following content:

package main
const http = require('http');
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, Kubernetes!\n');
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Create a Dockerfile:

FROM node:alpine
WORKDIR /app
COPY server.js .
EXPOSE 3000
CMD [“node”, “server.js”]

Build the Docker image:
Open a terminal in the directory where your Dockerfile and server.js are located, and run:

docker build -t simple-node-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-node-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: 3000
  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: 3000
  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: 3000
  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 *