Summary
We can follow these main steps to run our Node app in Kubernetes. In this post, I use Docker as the container runtime for Kubernetes.
- Write the app in Node.js.
- Write a Dockerfile and build a Docker image from it.
- Push the image to Docker Hub.
- Use the image above to create a Kubernetes Deployment.
Step 1: Write the app in Node.js
To make it simple, I wrote a web app using Express, which has only one API Endpoint:
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.get("/greeting", (req, res) => res.send({ message: "hello" }));
app.listen(port, () => console.log(`server listens on port ${port}`));
Step 2: Build a Docker image
We can use the Dockerfile
below to instruct Docker to build a container image for our app:
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ "node", "server.js" ]
We also need a .dockerignore
file so Docker will not copy unnecessary files to our image.
node_modules
.DS_Store
npm-debug.log
Now let's build the image by running this command. (<your username>
is your username on Docker Hub)
> docker build . -t <your username>/myapp
Step 3: Push the image to Docker Hub
The image is now created. Assume you have already had a Docker Hub account. You can log in using:
> docker login
We can now push it to Docker Hub:
> docker push <your username>/myapp
Step 4: Run the app in Kubernetes
I use minikube to set up a local Kubernetes cluster for testing purposes. If you are interested, you can follow the instruction on its homepage to set up on your machine.
So now we have a Docker image on Docker Hub, we can use it to create a Deployment:
# file deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-deployment
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: <your username>/myapp
ports:
- containerPort: 3000
Create the deployment by executing
> kubectl create -f deployment.yml
Check if your pod is running
> kubectl get pod -l app=myapp
NAME READY STATUS RESTARTS AGE
myapp-deployment-54865d44bf-h8t9r 1/1 Running 0 18m
myapp-deployment-54865d44bf-llsfs 1/1 Running 0 18m
myapp-deployment-54865d44bf-p7dkq 1/1 Running 0 18m
Check the log:
> kubectl logs myapp-deployment-54865d44bf-h8t9r myapp
server listens on port 3000
Top comments (0)