Tutorial: Getting Started with @kubernetes-client/node

Mike Turck - Sep 18 - - Dev Community

Tutorial: Getting Started with @kubernetes-client/node

Introduction

@kubernetes-client/node is the official Node.js client library for Kubernetes. It provides a powerful and flexible way to interact with Kubernetes clusters programmatically. This tutorial will guide you through the basics of using @kubernetes-client/node in your Node.js applications.

Installation

To get started, install the @kubernetes-client/node package using npm:

npm install @kubernetes-client/node
Enter fullscreen mode Exit fullscreen mode

Setting up the Client

First, let's import the necessary modules and create a Kubernetes client:

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

async function main() {
  const kc = new k8s.KubeConfig();
  kc.loadFromDefault();
  const client = kc.makeApiClient(k8s.CoreV1Api);

  // Your code here
}

main().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

This code creates a KubeConfig object, loads the default configuration (usually from ~/.kube/config), and creates an API client for the Core V1 API.

Listing Pods

Let's start with a simple example of listing pods in the default namespace:

async function listPods() {
  const kc = new k8s.KubeConfig();
  kc.loadFromDefault();
  const client = kc.makeApiClient(k8s.CoreV1Api);

  try {
    const res = await client.listNamespacedPod('default');
    console.log('Pods in default namespace:');
    for (const item of res.body.items) {
      console.log(`  - ${item.metadata.name}`);
    }
  } catch (err) {
    console.error('Error listing pods:', err);
  }
}

listPods();
Enter fullscreen mode Exit fullscreen mode

This function will list all pods in the default namespace.

Creating a Deployment

Now, let's create a simple deployment:

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

async function createDeployment() {
  const kc = new k8s.KubeConfig();
  kc.loadFromDefault();
  const client = kc.makeApiClient(k8s.AppsV1Api);

  const deployment = {
    metadata: {
      name: 'nginx-deployment'
    },
    spec: {
      replicas: 3,
      selector: {
        matchLabels: {
          app: 'nginx'
        }
      },
      template: {
        metadata: {
          labels: {
            app: 'nginx'
          }
        },
        spec: {
          containers: [{
            name: 'nginx',
            image: 'nginx:1.14.2',
            ports: [{
              containerPort: 80
            }]
          }]
        }
      }
    }
  };

  try {
    const res = await client.createNamespacedDeployment('default', deployment);
    console.log('Deployment created');
  } catch (err) {
    console.error('Error creating deployment:', err);
  }
}

createDeployment();
Enter fullscreen mode Exit fullscreen mode

This function creates a deployment with three replicas of an Nginx container.

Watching Resources

@kubernetes-client/node also supports watching resources for changes:

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

async function watchPods() {
  const kc = new k8s.KubeConfig();
  kc.loadFromDefault();
  const watch = new k8s.Watch(kc);

  try {
    const req = await watch.watch('/api/v1/namespaces/default/pods',
      {},
      (type, apiObj) => {
        console.log(`Pod ${apiObj.metadata.name} ${type}`);
      },
      (err) => {
        console.log(err);
      }
    );

    // Stop the watch after 30 seconds
    setTimeout(() => {
      req.abort();
    }, 30000);
  } catch (err) {
    console.error('Error watching pods:', err);
  }
}

watchPods();
Enter fullscreen mode Exit fullscreen mode

This function sets up a watch on pods in the default namespace and logs any changes for 30 seconds.

Conclusion

This tutorial has covered the basics of using @kubernetes-client/node, including setting up the client, listing resources, creating deployments, and watching for changes. The library offers many more capabilities for interacting with your Kubernetes clusters. For more advanced usage and a complete API reference, check out the @kubernetes-client/node documentation.

Remember to handle errors appropriately and consider using TypeScript for better type checking and autocompletion when working with the Kubernetes API objects.


If you enjoyed this content then check out Wonderfall, an interactive document editor with AI tools for parsing documents, viewing PDFs, saving highlights, and generating text.

. . . . . .
Terabox Video Player