Node.js: how to use the Kubernetes API

Node.js: how to use the Kubernetes API

In this article, we will explore how to use Kubernetes APIs in a Node.js application to interact with the cluster and perform resource management operations.

Kubernetes is an open-source system for orchestrating containers that facilitates the management, scalability, and distribution of containerized applications. One of Kubernetes' powerful features is its Application Programming Interface (API), allowing developers to interact with the system and automate resource management operations. In this article, we will explore how to use Kubernetes APIs in a Node.js application to interact with the cluster and perform resource management operations.

Prerequisites

Before getting started, make sure you have the following:

  1. Node.js and npm: Installed on your system.
  2. A Kubernetes cluster: Ensure you have access to a Kubernetes cluster. You can use a local cluster or one on a cloud service like Google Kubernetes Engine (GKE) or Amazon EKS.

Installation of the Node.js client for Kubernetes APIs

We will use the @kubernetes/client-node package, which provides a Node.js client for Kubernetes APIs.


npm install @kubernetes/client-node

Environment Configuration

To interact with Kubernetes APIs, we need a way to authenticate and authorize ourselves. Kubernetes uses a kubeconfig configuration file to manage authentication information and the cluster context. Copy this file into our Node.js application.


const k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromFile('path/to/your/kubeconfig');

Interacting with Kubernetes APIs

Once the environment is configured, and the Node.js client for Kubernetes APIs is installed, we can start interacting with the cluster. Let's see an example of how to get the list of nodes in the cluster:


const k8s = require('@kubernetes/client-node');

async function getNodes() {
  const kc = new k8s.KubeConfig();
  kc.loadFromFile('path/to/your/kubeconfig');

  const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

  try {
    const response = await k8sApi.listNode();
    const nodes = response.body.items;

    console.log('List of nodes in the cluster:');
    nodes.forEach(node => {
      console.log(`- Name: ${node.metadata.name}, IP Address: ${node.status.addresses[0].address}`);
    });
  } catch (error) {
    console.error('Error retrieving nodes:', error);
  }
}

getNodes();

This example uses the Node.js client for Kubernetes APIs to get the list of nodes in the cluster and print them to the console.

Examples of Advanced Operations

In addition to obtaining basic information, you can use Kubernetes APIs to perform many other operations, such as creating, updating, or deleting resources in the cluster. For example, we can create a new service:


async function createService() {
  const kc = new k8s.KubeConfig();
  kc.loadFromFile('path/to/your/kubeconfig');

  const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

  const serviceManifest = {
    apiVersion: 'v1',
    kind: 'Service',
    metadata: { name: 'new-service' },
    spec: {
      selector: { app: 'my-app' },
      ports: [{ protocol: 'TCP', port: 80, targetPort: 8080 }],
      type: 'LoadBalancer',
    },
  };

  try {
    const response = await k8sApi.createNamespacedService('default', serviceManifest);
    console.log('Service created successfully:', response.body);
  } catch (error) {
    console.error('Error creating the service:', error);
  }
}

createService();

This is just an example, and the possibilities are practically limitless. Kubernetes APIs offer a wide range of features for dynamically managing cluster resources.

Conclusion

In this article, we explored how to use Kubernetes APIs in a Node.js application to interact with the cluster. We started by configuring the environment and installing the Node.js client for Kubernetes APIs. Subsequently, we saw practical examples of obtaining basic information and performing advanced operations such as creating new services.

The combination of Kubernetes and Node.js provides a powerful and flexible approach to managing containerized resources, allowing developers to automate and simplify cluster management operations.