Prerequisites:*
- Install Node.js: https://nodejs.org/en/download/
- Install Docker: https://www.docker.com/products/docker-desktop
- Install Kubernetes CLI (kubectl): https://kubernetes.io/docs/tasks/tools/install-kubectl-macos/
- Install Minikube (for local Kubernetes cluster): https://minikube.sigs.k8s.io/docs/start/
- Install Terraform: https://learn.hashicorp.com/tutorials/terraform/install-cli
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"]
Build the Docker image: docker build -t hello-world-microservice
.
3: Set up Kubernetes deployment and service
- Start Minikube: minikube start
- 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"
}
}
- Initialize Terraform: terraform init
- Apply the Terraform configuration: terraform apply
5: Test the "Hello World" Microservice
- Get the Minikube IP:
minikube ip
- Get the service's external port:
kubectl get services -n hello-world
- 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.
- This doesn't work for few in that case you have to work should use
minikube tunnel
Top comments (0)