DEV Community

Ray Ch
Ray Ch

Posted on

Microservice with Kubernetes, Terraform, and Nest.js in Mac

Prerequisites:*

1. Creating Nest.js

I won't tell about Nest.js because it runs in 3000 port which already has pre-built "Hello World!" in the base boilerplate. So, I won't do anything new.

Install Nest.js CLI globally: npm install -g @nestjs/cli
Create a new Nest.js project: nest new hello-world-microservice

2: Containerize the Nest.js application

Create a Dockerfile in the project root with the following content:

FROM node:lts

RUN npm i -g pnpm

WORKDIR /app

COPY package.json pnpm-lock.yaml ./

RUN pnpm install

COPY . .

RUN pnpm run build

EXPOSE 3000

CMD ["pnpm", "run", "start:prod"]
Enter fullscreen mode Exit fullscreen mode

Build the Docker image: docker build -t hello-world-microservice .

3: Set up Kubernetes deployment and service

  1. Start Minikube: minikube start
  2. Set Docker environment: eval $(minikube docker-env)

4: Set up Terraform

This is the crucial part of running the micro service.

provider "kubernetes" {
  config_path = "~/.kube/config"
}

resource "kubernetes_namespace" "hello-world" {
  metadata {
    name = "hello-world"
  }
}

resource "kubernetes_deployment" "hello-world-microservice" {
  metadata {
    name      = "hello-world-microservice"
    namespace = kubernetes_namespace.hello-world.metadata.0.name
  }

  spec {
    replicas = 2

    selector {
      match_labels = {
        app = "hello-world-microservice"
      }
    }

    template {
      metadata {
        labels = {
          app = "hello-world-microservice"
        }
      }

      spec {
        container {
          name  = "hello-world-microservice"
          image = "hello-world-microservice"
          image_pull_policy = "Never"

          port {
            container_port = 3000
          }
        }
      }
    }
  }
}

resource "kubernetes_service" "hello-world-microservice" {
  metadata {
    name      = "hello-world-microservice"
    namespace = kubernetes_namespace.hello-world.metadata.0.name
  }

  spec {
    selector = {
      app = "hello-world-microservice"
    }

    port {
      port        = 80
      target_port = 3000
    }

    type = "LoadBalancer"
  }
}

Enter fullscreen mode Exit fullscreen mode
  1. Initialize Terraform: terraform init
  2. Apply the Terraform configuration: terraform apply

5: Test the "Hello World" Microservice

  1. Get the Minikube IP: minikube ip
  2. Get the service's external port: kubectl get services -n hello-world
  3. Combine the Minikube IP and the external port, and open the URL in your browser or use curl. For example, if Minikube IP is 192.168.49.2 and the external port is 32000, you can use curl http://192.168.49.2:32000 to see the "Hello World!" message.
  4. This doesn't work for few in that case you have to work should use minikube tunnel

Top comments (0)