In this tutorial, we will walk through the process of containerizing an Express.js application and deploying it on a Kubernetes cluster. This step-by-step guide is designed for developers looking to modernize their Node.js applications with containerization and orchestration.

Prerequisites

  • Node.js and npm installed
  • Docker installed and running
  • Kubernetes cluster (local or cloud-based)
  • kubectl configured to interact with your cluster

Step 1: Create an Express.js Application

Begin by setting up a basic Express.js app. Create a new directory and initialize a Node.js project:

Commands:

mkdir express-k8s

cd express-k8s

npm init -y

Install Express.js:

npm install express

Create an index.js file with the following content:

const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello, Kubernetes!'));
app.listen(port, () => console.log(`App listening on port ${port}`));

Step 2: Containerize the Application

Create a Dockerfile in your project directory:

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

Build the Docker image:

docker build -t express-k8s:latest .

Run the container locally to test:

docker run -p 3000:3000 express-k8s:latest

Step 3: Push Image to Container Registry

Tag your image for your registry (e.g., Docker Hub):

docker tag express-k8s:latest your-dockerhub-username/express-k8s:latest

Push the image:

docker push your-dockerhub-username/express-k8s:latest

Step 4: Create Kubernetes Deployment and Service

Define a deployment in a deployment.yaml file:

apiVersion: apps/v1
kind: Deployment
metadata:
name: express-deployment
spec:
replicas: 3
selector:
matchLabels:
app: express
template:
metadata:
labels:
app: express
spec:
containers:
- name: express
image: your-dockerhub-username/express-k8s:latest
ports:
- containerPort: 3000

And a service in service.yaml:

apiVersion: v1
kind: Service
metadata:
name: express-service
spec:
type: LoadBalancer
selector:
app: express
ports:
- protocol: TCP
port: 80
targetPort: 3000

Step 5: Deploy to Kubernetes

Apply the deployment and service:

kubectl apply -f deployment.yaml

kubectl apply -f service.yaml

Check the status:

kubectl get all

Conclusion

You have successfully containerized your Express.js application and deployed it on a Kubernetes cluster. This setup allows for scalable, reliable, and manageable deployments. Continue exploring Kubernetes features like ingress, persistent storage, and autoscaling to enhance your deployment further.