DEV Community

GaneshMani
GaneshMani

Posted on • Originally published at cloudnweb.dev on

Kubernetes for Nodejs developers

Do you keep hearing the word Kubernetes in the tech community and you couldn't understand what, why, and how of Kubernetes?. Well, you are in the right place, my friend. I was like that, when people around me talks about Kubernetes and couldn't understand what they talk about. So, In this article, let's understand Kubernetes with nodejs application development.

Note: there are a lot of articles out there explains about Kubernetes and it's a workflow in detail. but the main purpose of writing this blog is to explain Kubernetes to a guy like me who wants to learn Kubernetes in an easy and understandable way.

Before, getting into the concept of Kubernetes. let's understand what is Kubernetes and why it's so popular nowadays.

I assume that you have a basic understanding of what is docker, containers, and how to build docker images for nodejs application.

Prerequisites

Docker Desktop installed and Kubernetes enabled on your machine.

Related Articles

How to Find Project Ideas for Web development

Building a Production-grade Nodejs,GraphQL and TypeScript Server with CI/CD Pipeline

What is Kubernetes?

Let's try to understand Kubernetes with simple terms and scenarios. At the beginning of application development, we tend to deploy our application manually just by creating a server in the cloud and deploy our application with either through git or file transfer protocol such as FileZilla.

Traditional Server

After the evolution of containers and Docker, application deployment will be like wrapping our application code insider docker containers and deploy them in the server. it solved a lot of problems for us such as installing the dependencies manually and resolve the conflicts that come in that way.

Still, there are some problems that need to solved manually. they are, if we have replicas of the containers, we need to manage them. like if one goes down. we need to restart the replica set and keep checking the health of the cluster.

Then comes Kubernetes, which helps us to manage the containers within a system. Kubernetes helps us to manage the container in a systematic way. Once configured, it will take care of the containers without you need to worry about the containers.

Architecture

Some of the benefits of using Kubernetes are,

  • Service Discovery - Let's say you have a Container for User REST API and Container for Another domain REST API Container. to make it communicate, you need to make the service available to another one. Kubernetes helps us in that process easier. we will see about this in the later part of this article.
  • Container Orchestration - If you want to replicas of your container to be running all the time irrespective of failure. Kubernetes solves that problem out of the box. you don't need to worry about that at all. it will make sure that specified replica's available all the time.

Basics of Kubernetes

Alright!! we reached one of the important topics in the article. Let's see what we need to know in Kubernetes before application development with Kubernetes.

Core Concepts

Firstly, we have master and node,

Master & Node

Node is a simply a virtual machine the server. just like how we create a virtual machine. Kubernetes manage the VM as a node.

Master is a controller that controls all the operations in the node and it also manages all the configurations of nodes.

Inside the Node, we have Pod and Container.

Pod & Container

Pod in Kubernetes is a collection of containers. most of the time pod will contain only one container. only on some special scenarios, you might need to create multiple containers in the pod.

so far, we have the container inside the pod. but, how do they communicate between the containers? for example, the Nodejs application needs to connect with MongoDB for data access. how does it happen in Kubernetes?

There comes the need of Service in Kubernetes.

Service

Service helps us with the communication between the containers. Let me tell you one thing. when i read about services in Kubernetes. I had this question of "Why?", Why do we need other resources to manage the communication? Can't a container talk directly with another container?.

Then I found out the real purpose of Services in Kubernetes. Let's say you have the Container A with IPAddress 192.16.3.2 and Container B communicates with Container A using this IPAddress. After some time, your Container A dies and Kubernetes recreates a new container for you on the Node. Now, the IPAddress will be different for the Container. Now, how can ContainerB communicates with A with the IPAddress is different

This is the main purpose of having the Kubernetes Service.

Deployment

Deployment is a way to create pods and containers in Kubernetes. it read the configuration file and pull the docker images from the hub and create the container out of it.

Most of the time, you will be writing the YAML configuration for Service and Deployment Resources*.* Sometimes, you might need to create some other resources.

Running Nodejs with Kubernetes

Here we have a simple nodejs application to deploy using Kubernetes. create app.js and add the following code,

const express = require("express")

const app = express()

app.get("/", (req, res) => {
  res.send({
    data: "Kubernetes is Awesome",
  })
})

const PORT = process.env.PORT || 8080

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})

After that, create a folder to write the kubernetes configuration. infra/app-deploy.yaml

---
apiVersion: v1
kind: Service
metadata:
  name: my-node-app-service
  labels:
    app: my-node-app-service
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 8080
  type: LoadBalancer
  selector:
    app: mynodeapp
---

Let's break it down one by one. For any resources that you create for kubernetes. it always start with apiVersion and kind

apiVersion: v1
kind: Service

Here, we mention the kind as Service which create the service for us. there are four type of Service in the kubernetes.

  1. ClusterIP - it exposes the service to be accessed within the cluster. you can access this service using the IPAddress of the cluster.
  2. NodePort - NodePort helps us to connect Pods to external IP's. it maps the Node Port with Pod Port which helps to access the Pod externally. Note: Port of Node ranges from 30000 - 32767
  3. LoadBalancer - it is similar to NodePort except that it balances the load with multiple ports.
  4. ExternalName - it maps the service and pods to the CNAME record

Here, we will be using LoadBalancer Service to map the NodePort with Containers.

Coming back to the configuration. then we have, metadata which helps to identify the service.

metadata:
  name: my-node-app-service
  labels:
    app: my-node-app-service

After that, we have the main part of the configuration which is spec. Here, we specify the type of service along with the port and target port

spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 8080
  type: LoadBalancer
  selector:
    app: mynodeapp

Service WorkFlow

Service NodePort

On the above diagram, we need to access the pod from external IP. to do that, we configure Service which maps the port between Pod and NodePort.

Service maps the Port with the targetPort and it maps with NodePort to route the traffic into the Pod.

So far, we have seen how to configure the Service .let's see how to create the Pods and Containers inside of it. To do that, we need to create Deployment Resources.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-deployment
  labels:
    app: mynodeapp
spec:
  replicas: 2
  selector:
    matchLabels:
      app: mynodeapp
  template:
    metadata:
      labels:
        app: mynodeapp
    spec:
      containers:
        - name: mynodeapp
          image: ganeshmani009/nodesample
          ports:
            - containerPort: 8080
          imagePullPolicy: Always
          env:
            - name: PORT
              value: "8080"
            - name: MONGODB_URL
              value: mongodb://mongo:27017/sampledb

This seems to be a bit long. right?. let's try to break it down and understand better. just like before, we have the basic information about the resource,

# configuration
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-deployment
  labels:
    app: mynodeapp

After that, we have spec with configuration for the template and replicaSet

# Configuration for the replica set
replicas: 2
  selector:
    matchLabels:
      app: mynodeapp

Then, we have the configuration for the pod, which pulls the image from the docker hub and creates the container inside the pod.

template:
  metadata:
    labels:
      app: mynodeapp
  spec:
    containers:
      - name: mynodeapp
        image: ganeshmani009/nodesample
        ports:
          - containerPort: 8080
        imagePullPolicy: Always
        env:
          - name: PORT
            value: "8080"
          - name: MONGODB_URL
            value: mongodb://mongo:27017/sampledb

Once you complete the configuration, run the command in the terminal.

kubectl apply -f app-deploy.yaml

Pod Deploy Command

you can check the pods using the command

kubectl get pods

Get Pods

Since, we configured replicaSet as 2. it creates two pods for us. to check the service.

kubectl get service

Get Service

Conclusion

we just scratched the surface in the Kubernetes world. In the upcoming article, we will see how to connect the MongoDB with nodejs application in Kubernetes. we will also see some use-cases on how nodejs and Kubernetes used in production. Until then, Happy Coding :-)

Top comments (0)