Deploying a NestJS application with Kubernetes can significantly enhance its scalability, reliability, and manageability. This step-by-step guide provides a comprehensive overview of how to deploy your NestJS app using Kubernetes, from initial setup to production deployment.

Prerequisites

  • Basic knowledge of NestJS framework
  • Docker installed on your machine
  • Kubernetes cluster (local or cloud-based)
  • kubectl CLI configured to access your cluster
  • Access to a container registry (Docker Hub, GCR, etc.)

Step 1: Containerize Your NestJS Application

Create a Dockerfile in your NestJS project root:

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .

RUN npm run build

EXPOSE 3000

CMD ["node", "dist/main"]

Build and push your Docker image:

docker build -t yourusername/nestjs-app:latest .
docker push yourusername/nestjs-app:latest

Step 2: Create Kubernetes Deployment and Service

Define a deployment YAML file (nestjs-deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nestjs-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nestjs
  template:
    metadata:
      labels:
        app: nestjs
    spec:
      containers:
      - name: nestjs
        image: yourusername/nestjs-app:latest
        ports:
        - containerPort: 3000

Create a service YAML file (nestjs-service.yaml):

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

Step 3: Deploy to Kubernetes

Apply the deployment and service files:

kubectl apply -f nestjs-deployment.yaml
kubectl apply -f nestjs-service.yaml

Verify the deployment:

kubectl get deployments
kubectl get services

Step 4: Access Your Application

If you are using a cloud provider, the LoadBalancer service will provide an external IP address. Retrieve it with:

kubectl get service nestjs-service

Open your browser and navigate to the external IP to see your NestJS app running on Kubernetes.

Conclusion

Deploying NestJS with Kubernetes involves containerizing your app, creating deployment and service configurations, and managing the deployment process. This setup ensures your application is scalable, resilient, and ready for production environments.