K8s: deploying a Node.js application with a custom image

Ian Oliv

Ian Oliv / December 27, 2021

2 min read––– views

K8s: deploying a Node.js app

On this post we will deploy a Node.js app to a Kubernetes cluster. to deploy a Node.js app to a Kubernetes cluster, we will use the kubectl command line tool. After installing the kubectl command line tool, we will create a Kubernetes cluster and deploy a Node.js app to it. deploying a Node.js app to a Kubernetes cluster has several steps:

  • Step 1: create a node js project
  • Step 2: create a Dockerfile
  • Step 3: create a kubernetes deployment and service

Step 1: create a node js project

> touch app.js
// app.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
});
server.listen(3000);

Step 2: create a Dockerfile

FROM node:8
WORKDIR /usr/src/app
COPY . .
expose 3000
CMD ["node", "app.js"]

docker build -t node-simple-app . && docker push node-simple-app

node-simple-app -> image name

Step 3: create a kubernetes deployment and service

# deployment-service.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-node  # name of the deployment
spec:
    replicas: 1
    selector:
        matchLabels:
        app: hello-node
    template:
        metadata:
        labels:
            app: hello-node
        spec:
        containers:
        - name: node-simple-appe
            image: node-simple-app
            imagePullPolicy: Always
            ports:
            - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: hello-node
spec:
    type: NodePort
    ports:
    - port: 3000
        targetPort: 3000
    selector:
        app: hello-node # name of the deployment

Step 4: deploy the app

> kubectl apply -f deployment-service.yaml
depoyment "hello-node" created
service "hello-node" created