Kubernetes and its implementation using Node.js

Kubernetes and its implementation using Node.js

Introduction Paragraph.

Kubernetes has become an integral part of modern web services, allowing for the quick and efficient deployment of containerized applications. In this article, we will provide an overview of Kubernetes, discuss its architecture and components, and showcase how to implement a Kubernetes system using Node.js. We will also explore the differences between Kubernetes and Docker and explain how to set up Minikube, a tool used to implement a virtual machine for Kubernetes on your local machine.

Key takeaways:

  1. Being able to learn what Kubernetes is and learning more about its components.

  2. Bring in Docker and how it compares to Kubernetes.

  3. Showcase Kubernetes using Node.js.

Objectives

  • What is Kubernetes and what it helps?

  • Overview of Kubernetes.

  • Implementing a Kubernetes system using Node.js.

What is Kubernetes?

It is an open-source container-orchestration system that manages the containerized applications and takes care of the automated deployment, storage, scaling, scheduling, load balancing, updates(rolling updates), self-healing, batch-execution and monitoring of containers across clusters of hosts.

What can Kubernetes do for you?

With modern web services, users expect applications to be available 24/7, and developers expect to deploy new versions of those applications several times a day. Containerization helps package software to serve these goals, enabling applications to be released and updated without downtime. Kubernetes helps you make sure those containerized applications run where and when you want, and helps them find the resources and tools they need to work. Kubernetes is a production-ready, open-source platform designed with Google's accumulated experience in container orchestration, combined with best-of-breed ideas from the community.

Docker vs Kubernetes

Although there is a difference between the two, most people like to quantify that they do the same work. So below entails what now Docker is and the differences between the two. Though you can be able to implement Docker in a Kubernetes cluster and we will be able to see this as we progress.

Docker is a containerization platform that allows developers to create, package, and deploy applications as lightweight containers. These containers are isolated environments that contain everything needed to run an application, including code, dependencies, libraries, and system tools.

Kubernetes, on the other hand, is a container orchestration platform that automates the deployment, scaling, and management of containerized applications. Kubernetes can manage multiple containers and coordinate their interactions, making it easier to deploy and manage complex applications.

Differences between Docker and Kubernetes

DockerKubernetes
It is a containerization platform.It is a container orchestration platform.
Provides a simple and easy-to-use containerization solution.Provides a more complex and feature-rich orchestration solution.
Primarily used for deploying single containers.Designed for managing multiple containers across multiple hosts.
Provision of basic scaling functionality.Provision of advanced scaling capabilities, such as automatic scaling based on resource usage.
Presence of limited monitoring capabilities.Provides built-in monitoring and logging functionality.

Kubernetes Architecture Components

  1. Master Node

  2. Worker Node - contains the pods

The two are connected using a virtual network.

The master node is used as the main component in this and has the following four components, namely:

  1. API Server - it enables interactions between the cluster which is done using the UI, Kubernetes API or the CLI (Kubectl).

  2. Scheduler - ensures the Pods placements within the worker nodes as well as managing the resources in the nodes.

  3. Controller Manager - keep note/track of what happens in the cluster. It also consists of the node controller, replication controller, endpoints controller, and service account and token controllers.

  4. Etcd - it is the Kubernetes backing storage for the information in the structure. It is the database based on the master node.

The worker node is the sub-component that has the following components:

  1. Kublet - an agent running on the worker node which monitors the state of a Pod, and if it is not in the desired state, a redeploy is made on the same node or another healthy node.

  2. Kube-proxy - is the implementation of the network proxy, which now exposes the services to the outside world and a load-balancer.

  3. Container runtime/Docker - since Kubernetes cannot directly handle containers, it requires a Container runtime and that is where the container runtimes such as Docker come to solve this.

Pod Container Components

  1. Pod - this is the abstraction of a container(hosts the pod). It contains the application and the database. It can only run one application.

  2. Service - highlights the IP address of both the application and the database. Service helps to maintain the IP addresses of both of them when either the application or the database crashes and a new one is set to replace it. It is a permanent IP address that is attached to the existing application and database and is assigned to any new component that comes up as a replacement for the application or database.

  3. Ingress - is the external linkage for communication. It forwards requests to the Service.

  4. ConfigMap - sets up the environment of the application and the database.

  5. Secret - sets up confidential environment variables such as usernames and passwords of the application and the database.

  6. Volume - it is the storage of the pod(stores the status of the pod) This is necessary since Kubernetes doesn’t manage data persistence. Keeps a backup of the application and database.

  7. Deployment - deployment of a stateless pod. It is a blueprint for “application” pods. It is an abstraction of pods. If you want to create a replica of the pod, the blueprint is issued(Deployment) from which you can declare the number of replicas that you would like to have. It only replicates the application.

  8. Statefulset - it replicates pods like Deployments but also synchronizes the database so that there are no database inconsistencies.

You can create a deployment on either:

  1. Your Local Machine

  2. On Cloud using Minikube

Setting up Minikube

Minikube is used to implement a Virtual Machine on your computer which can be used to implement Kubernetes.

In this, both the master and worker processes run on one node thus removing the limitations of insufficient resources on your local machine.

The node has a Docker runtime pre-installed.

Pre-requisites for this

  1. Minikube

  2. Docker

Installation

You can download Minikube from https://minikube.sigs.k8s.io/docs/start/

And download Docker from https://minikube.sigs.k8s.io/docs/drivers/

Setting up the environment

You need to run the command line as an administrator.

Then run minikube start for basic or minikube start —driver docker

minikube start
minikube start —driver docker

After it has set up Minikube and Docker, you can confirm this by running

minikube status

Creating a Demo Project

We will deploy a database based on MongoDB and a web application that will be connected to the database using Service through ConfigMap and Secret.

Here's a step-by-step guide to creating a Kubernetes deployment that includes a Node.js app and MongoDB database using YAML files and Minikube.

Step 1: Install Minikube and start a cluster

If you haven't already, install Minikube by following the instructions on their website. Then start a new cluster by running the following command:

minikube start

Step 2: Create a MongoDB deployment

Create a new file called mongo.yaml with the following content:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo
  labels:
    app: mongo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongo
  template:
    metadata:
      labels:
        app: mongo
    spec:
      containers:
      - name: mongo
        image: mongo
        ports:
        - containerPort: 27017
        env:
        - name: MONGO_INITDB_ROOT_USERNAME
          valueFrom:
            secretKeyRef:
              name: mongo-secret
              key: mongo-user
        - name: MONGO_INITDB_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mongo-secret
              key: mongo-password
        volumeMounts:
        - name: mongo-data
          mountPath: /data/db
      volumes:
      - name: mongo-data
        hostPath:
          path: /mnt/data

---
apiVersion: v1
kind: Service
metadata:
  name: mongo-service
spec:
  selector:
    app: mongo
  ports:
    - protocol: TCP
      port: 27017
      targetPort: 27017

This YAML file defines a Kubernetes deployment for MongoDB. It creates a single replica of the Mongo container, which uses the official Mongo Docker image. The container is configured to listen on port 27017, which is the default MongoDB port. It also creates a persistent volume for the database data, mounted on the host machine at /mnt/data.

To log in to your MongoDB cloud, you require to use your username and password. We can be able to configure this through the Secret and ConfigMap components. You need to create the file mongo-secret.yaml for the secret information.

apiVersion: v1
kind: Secret
metadata:
  name: mongo-secret
type: Opaque
data:
  mongo-user: <your_mongodb_userid>
  mongo-password: <your_mongodb_password>

Below is the mongo-config.yaml for the ConfigMap.

apiVersion: v1
kind: ConfigMap
metadata:
  name: mongo-config
data:
  mongo-url: mongo-service

To create the MongoDB deployment, run the following command:

kubectl apply -f mongo.yaml

Step 3: Create a Node.js deployment

Create a new file called web-app.yaml with the following content:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
  labels:
    app: web-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
    spec:
      containers:
      - name: web-app
        image: <your-node-image>
        ports:
        - containerPort: 3000
        env:
        - name: MONGO_URL
          valueFrom:
            secretKeyRef:
              name: mongo-secret
              key: mongo-user
        - name: USER_PWD
          valueFrom:
            secretKeyRef:
              name: mongo-secret
              key: mongo-password 
        - name: DB_URL
          valueFrom:
            configMapKeyRef:
              name: mongo-config
              key: mongo-url

---
apiVersion: v1
kind: Service
metadata:
  name: webapp-service
spec:
  type: NodePort
  selector:
    app: webapp
  ports:
    - protocol: TCP
      port: 3000
      targetPort: 3000
      nodePort: 30100

This YAML file defines a Kubernetes deployment for the Node.js app. It creates a single replica of the node container, which uses your custom Node.js Docker image (replace <your-node-image> with your actual image name). The container is configured to listen on port 3000, which is the default port for Node.js apps. It also sets an environment variable MONGO_URL to connect to the MongoDB database.

To create the Node.js deployment, run the following command:

kubectl apply -f node.yaml

Step 4: Expose the Node.js service

Create a new file called web-app-service.yaml with the following content:

apiVersion: v1
kind: Service
metadata:
  name: node
spec:
  selector:
    app: node
  ports:
  - name: http
    port: 3000
    targetPort: 3000
  type: NodePort

This YAML file defines a Kubernetes service for the Node.js app. It selects the node deployment using the app label and exposes it on port 3000. It also sets the service type to NodePort, which makes the service accessible on a random port on the Minikube cluster.

To create the Node.js service, run the following command:

kubectl apply -f node-service.yaml

Conclusion

In conclusion, Kubernetes has revolutionized the way web services are deployed, and its popularity continues to grow. By understanding its architecture and components, you can leverage its power to efficiently deploy containerized applications. Through the implementation of a Kubernetes system using Node.js, we have demonstrated how to utilize Kubernetes to its fullest potential. With the help of Minikube, you can easily set up a virtual machine on your local machine and start experimenting with Kubernetes today.