Dark Mode On / Off

Simple Nodejs Application on Kubernetes

Here’s a simple example of a Node.js application that you can deploy to Kubernetes. This example will create a basic HTTP server that responds with “Hello, World!” to all requests.

First, create a new directory for your project and navigate into it:

mkdir nodejs-kubernetes
cd nodejs-kubernetes

Next, create a new file named server.js and add the following code:

const http = require('http');

const hostname = '0.0.0.0';
const port = 3000;

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

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

This code creates a basic HTTP server that listens on port 3000 and responds with “Hello, World!” to all requests.

Next, create a Dockerfile in the same directory with the following content:

FROM node:14

WORKDIR /app

COPY package.json .
RUN npm install

COPY . .

CMD [ "node", "server.js" ]

This Dockerfile defines a Docker image that uses the official Node.js 14 image, sets the working directory to /app, copies the package.json file, installs dependencies, copies the rest of the application files, and then runs the server.js file.

Next, create a package.json file in the same directory with the following content:

{
  "name": "nodejs-kubernetes",
  "version": "1.0.0",
  "description": "A simple Node.js application for Kubernetes",
  "main": "server.js",
  "dependencies": {
    "http": "^0.0.1"
  }
}

This package.json file defines the name and dependencies of your application.

Now, you can build the Docker image by running the following command in your terminal:

docker build -t nodejs-kubernetes .

Once the image is built, you can run it locally to test it:

docker run -p 3000:3000 nodejs-kubernetes

Finally, to deploy your application to Kubernetes, you’ll need to create a Kubernetes deployment and service manifest. Here’s an example manifest (deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nodejs-kubernetes
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nodejs-kubernetes
  template:
    metadata:
      labels:
        app: nodejs-kubernetes
    spec:
      containers:
        - name: nodejs-kubernetes
          image: nodejs-kubernetes
          ports:
            - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: nodejs-kubernetes
spec:
  selector:
    app: nodejs-kubernetes
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
  type: LoadBalancer

Apply this manifest to your Kubernetes cluster using kubectl apply -f deployment.yaml. This will create a deployment and a service for your Node.js application.

You should now be able to access your application using the external IP of the service on port 80.

Leave a Reply

Your email address will not be published. Required fields are marked *