Deploying high-performance Node.js applications requires a robust and scalable infrastructure. Docker and Kubernetes have become essential tools for developers aiming to streamline deployment processes and ensure application resilience. This article provides a comprehensive workflow for deploying Node.js apps on Docker containers orchestrated by Kubernetes.

Prerequisites and Setup

Before beginning, ensure that you have the following installed:

  • Node.js and npm
  • Docker
  • Kubernetes cluster (local or cloud-based)
  • kubectl command-line tool

Verify installations by running:

node -v, npm -v, docker --version, and kubectl version.

Building the Node.js Application

Create a simple Node.js app or use an existing one. For illustration, here is a basic server:

index.js

const http = require('http');

const server = http.createServer((req, res) => { res.end('Hello, Kubernetes!'); });

server.listen(3000, () => { console.log('Server listening on port 3000'); });

Creating a Docker Image

Write a Dockerfile to containerize the application:

Dockerfile

FROM node:14

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["node", "index.js"]

Build the Docker image:

docker build -t node-k8s-app .

Deploying to Kubernetes

Create a deployment YAML file:

deployment.yaml

apiVersion: apps/v1

kind: Deployment

metadata:

name: node-k8s-deployment

spec:

replicas: 3

selector:

matchLabels:

app: node-k8s-app

template:

metadata:

labels:

app: node-k8s-app

spec:

containers:

- name: node-k8s-container

image: node-k8s-app:latest

ports:

- containerPort: 3000

Apply the deployment:

kubectl apply -f deployment.yaml

Create a service YAML file to expose the deployment:

service.yaml

apiVersion: v1

kind: Service

metadata:

name: node-k8s-service

spec:

type: LoadBalancer

selector:

app: node-k8s-app

ports:

- port: 80

targetPort: 3000

Deploy the service:

kubectl apply -f service.yaml

Monitoring and Scaling

Use Kubernetes commands to monitor the deployment and scale as needed:

kubectl get pods

kubectl scale --replicas=5 deployment/node-k8s-deployment

Conclusion

Deploying high-performance Node.js applications on Docker and Kubernetes enables scalable, resilient, and manageable infrastructure. Following this workflow ensures efficient deployment, monitoring, and scaling of your applications in production environments.