Kubernetes Build and Deploy NodeJS Application and Scale It

Kubernetes has become the de facto standard for container orchestration. If you’re looking to scale a NodeJS application efficiently while ensuring high availability, Kubernetes is the perfect solution. In this guide, we’ll walk you through building, deploying, and scaling a NodeJS application using Kubernetes. Let’s dive in step by step!

Let’s jump right into deploying a NodeJS application using Kubernetes.


Step 1: Build Your NodeJS Application

Create a Simple NodeJS App

Here’s a basic Express.js app:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello, Kubernetes!');
});

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

Save this as app.js.


Create a Dockerfile

Containerize your application with Docker. Add the following to a file named Dockerfile:

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]

Build and Push the Docker Image

Run the following commands to build and push your Docker image:

docker build -t <your-dockerhub-username>/nodejs-app:v1 .
docker login
docker push <your-dockerhub-username>/nodejs-app:v1

Replace <your-dockerhub-username> with your Docker Hub username.


Step 2: Deploy to Kubernetes

Create a Deployment YAML

Write a deployment file deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nodejs-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nodejs-app
  template:
    metadata:
      labels:
        app: nodejs-app
    spec:
      containers:
      - name: nodejs-app
        image: <your-dockerhub-username>/nodejs-app:v1
        ports:
        - containerPort: 3000

Apply the Deployment

Use kubectl to apply the deployment:

kubectl apply -f deployment.yaml

Expose the Application

Create a service to expose the deployment:

kubectl expose deployment nodejs-app --type=LoadBalancer --port=80 --target-port=3000

Step 3: Scale the Application

Scale Manually

Increase the number of replicas to handle more traffic:

kubectl scale deployment nodejs-app --replicas=5

Set Up Horizontal Pod Autoscaler (HPA)

Enable automatic scaling based on CPU usage:

kubectl autoscale deployment nodejs-app --cpu-percent=50 --min=2 --max=10

Step 4: Test Your Setup

Access the Application

Get the external IP of the service:

kubectl get svc

Open the IP in your browser. You should see Hello, Kubernetes!.


Simulate Traffic

Use a load testing tool like Apache Bench or wrk to simulate traffic and observe scaling:

ab -n 1000 -c 50 http://<external-ip>/

Step 5: Monitor and Manage

Leverage tools like Prometheus and Grafana for monitoring. Use Kubernetes Dashboard for real-time management.