Convert Figma logo to code with AI

kubernetes-client logojavascript

Javascript client

2,001
508
2,001
36

Top Related Projects

Go client for Kubernetes.

Repo for the controller-runtime subproject of kubebuilder (sig-apimachinery)

6,694

Official Python client library for kubernetes

3,537

Official Java client library for kubernetes

23,209

Complete container management platform

26,764

The Kubernetes Package Manager

Quick Overview

The kubernetes-client/javascript repository is an official Kubernetes client library for JavaScript. It provides a way to interact with Kubernetes clusters programmatically using JavaScript or TypeScript, allowing developers to manage Kubernetes resources and perform operations on clusters from within their Node.js applications.

Pros

  • Official Kubernetes client, ensuring compatibility and up-to-date support
  • Supports both JavaScript and TypeScript
  • Provides a high-level abstraction for Kubernetes API operations
  • Includes support for watch operations and custom resource definitions (CRDs)

Cons

  • Documentation could be more comprehensive and include more examples
  • Learning curve can be steep for developers new to Kubernetes
  • Limited community support compared to some other language clients
  • May require frequent updates to keep up with Kubernetes API changes

Code Examples

  1. Creating a Kubernetes client:
const k8s = require('@kubernetes/client-node');

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
  1. Listing pods in a namespace:
async function listPods(namespace) {
  try {
    const res = await k8sApi.listNamespacedPod(namespace);
    console.log('Pods:', res.body.items);
  } catch (err) {
    console.error('Error listing pods:', err);
  }
}
  1. Creating a deployment:
const appsV1Api = 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' }]
      }
    }
  }
};

async function createDeployment(namespace) {
  try {
    const res = await appsV1Api.createNamespacedDeployment(namespace, deployment);
    console.log('Deployment created');
  } catch (err) {
    console.error('Error creating deployment:', err);
  }
}

Getting Started

  1. Install the library:

    npm install @kubernetes/client-node
    
  2. Import and create a client:

    const k8s = require('@kubernetes/client-node');
    const kc = new k8s.KubeConfig();
    kc.loadFromDefault();
    const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
    
  3. Use the client to interact with your Kubernetes cluster:

    async function getNamespaces() {
      const res = await k8sApi.listNamespace();
      console.log('Namespaces:', res.body.items.map(ns => ns.metadata.name));
    }
    
    getNamespaces().catch(console.error);
    

Competitor Comparisons

Go client for Kubernetes.

Pros of client-go

  • Written in Go, offering better performance and native integration with Kubernetes (also written in Go)
  • More mature and actively maintained, with frequent updates and a larger community
  • Provides more comprehensive coverage of Kubernetes API features

Cons of client-go

  • Steeper learning curve for developers not familiar with Go
  • Requires compilation, which can be a drawback for some deployment scenarios
  • Less suitable for web-based or JavaScript-centric projects

Code Comparison

client-go (Go):

clientset, err := kubernetes.NewForConfig(config)
pod, err := clientset.CoreV1().Pods("default").Get(context.TODO(), "pod-name", metav1.GetOptions{})

javascript (JavaScript):

const kc = new k8s.KubeConfig();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
const pod = await k8sApi.readNamespacedPod('pod-name', 'default');

Both libraries provide similar functionality for interacting with Kubernetes APIs, but client-go offers a more idiomatic approach for Go developers, while javascript is more suitable for JavaScript-based projects and environments.

Repo for the controller-runtime subproject of kubebuilder (sig-apimachinery)

Pros of controller-runtime

  • Written in Go, providing better performance and native Kubernetes integration
  • Designed specifically for building Kubernetes controllers and operators
  • Offers higher-level abstractions for common controller patterns

Cons of controller-runtime

  • Limited to Go language, less accessible for JavaScript developers
  • Steeper learning curve for developers not familiar with Go or Kubernetes internals
  • Less suitable for simple client-side applications or scripts

Code Comparison

controller-runtime (Go):

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
err = (&MyReconciler{
    Client: mgr.GetClient(),
    Log:    ctrl.Log.WithName("controllers").WithName("My"),
}).SetupWithManager(mgr)

javascript (JavaScript):

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
const res = await k8sApi.listNamespacedPod('default');

controller-runtime is tailored for building complex Kubernetes controllers and operators in Go, offering powerful abstractions and native integration. javascript provides a more accessible JavaScript client for interacting with Kubernetes APIs, suitable for simpler applications and scripts. The choice between them depends on the specific use case, language preference, and complexity of the desired Kubernetes interaction.

6,694

Official Python client library for kubernetes

Pros of python

  • More mature and stable with a longer development history
  • Better documentation and examples for various use cases
  • Larger community and more active development

Cons of python

  • Slower execution speed compared to JavaScript
  • Less suitable for frontend or browser-based applications
  • Steeper learning curve for developers coming from web development backgrounds

Code Comparison

Python:

from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces()
for pod in pods.items:
    print(f"{pod.metadata.namespace}\t{pod.metadata.name}")

JavaScript:

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

const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

k8sApi.listPodForAllNamespaces().then((res) => {
  res.body.items.forEach((pod) => {
    console.log(`${pod.metadata.namespace}\t${pod.metadata.name}`);
  });
});

Both examples demonstrate listing pods across all namespaces, showcasing similar functionality but with language-specific syntax and patterns. The Python version uses synchronous code, while the JavaScript version uses Promises for asynchronous operations.

3,537

Official Java client library for kubernetes

Pros of java

  • Strongly typed, offering better compile-time error checking
  • More mature and feature-complete, with broader API coverage
  • Better performance for large-scale applications

Cons of java

  • More verbose syntax, requiring more code for similar operations
  • Steeper learning curve, especially for developers new to Java
  • Slower development cycle due to compilation requirements

Code Comparison

java:

ApiClient client = Config.defaultClient();
CoreV1Api api = new CoreV1Api(client);
V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
}

javascript:

const k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
const res = await k8sApi.listPodForAllNamespaces();
res.body.items.forEach(pod => console.log(pod.metadata.name));

The java client offers a more structured approach with explicit type declarations, while the javascript client provides a more concise and flexible syntax. The javascript version leverages async/await for better readability in asynchronous operations.

23,209

Complete container management platform

Pros of Rancher

  • Provides a complete container management platform with a user-friendly GUI
  • Offers multi-cluster management and supports multiple Kubernetes distributions
  • Includes built-in security features and access control

Cons of Rancher

  • More complex setup and resource-intensive compared to a simple client library
  • Steeper learning curve for users new to container orchestration
  • May introduce additional overhead for small-scale deployments

Code Comparison

Rancher (YAML configuration):

rancher:
  image: rancher/rancher:latest
  ports:
    - "80:80"
    - "443:443"
  volumes:
    - /opt/rancher:/var/lib/rancher

Kubernetes JavaScript Client:

const k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

Summary

Rancher is a comprehensive container management platform, while the Kubernetes JavaScript Client is a lightweight library for interacting with Kubernetes clusters. Rancher offers a more feature-rich solution with a GUI, multi-cluster management, and built-in security features. However, it requires more resources and has a steeper learning curve. The JavaScript Client is simpler to use and integrate into existing applications but lacks the advanced features and visual interface of Rancher. Choose based on your project's scale, complexity, and specific requirements.

26,764

The Kubernetes Package Manager

Pros of Helm

  • Provides package management for Kubernetes applications
  • Offers templating and versioning for complex deployments
  • Has a large ecosystem of pre-built charts for common applications

Cons of Helm

  • Steeper learning curve for beginners
  • Requires additional infrastructure (Tiller) in older versions
  • May introduce complexity for simple deployments

Code Comparison

Helm (Chart.yaml):

apiVersion: v2
name: my-app
description: A Helm chart for Kubernetes
version: 0.1.0
appVersion: 1.16.0

JavaScript Client:

const k8s = require('@kubernetes/client-node');
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

Summary

Helm is a package manager for Kubernetes that simplifies deployment and management of applications, while the JavaScript Client provides a programmatic interface for interacting with Kubernetes clusters. Helm excels in managing complex applications with its templating and versioning capabilities, but may be overkill for simple deployments. The JavaScript Client offers more flexibility for custom automation and integration but requires more manual configuration.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Javascript Kubernetes Client information

Build Status Client Capabilities Client Support Level Build and Deploy Docs

The Javascript clients for Kubernetes is implemented in typescript, but can be called from either Javascript or Typescript. The client is implemented for server-side use with Node.

The request library is currently being swapped to fetch. See the fetch migration docs for more information and progress.

Installation

npm install @kubernetes/client-node

Example code

List all pods

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

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

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

const main = async () => {
    try {
        const podsRes = await k8sApi.listNamespacedPod('default');
        console.log(podsRes.body);
    } catch (err) {
        console.error(err);
    }
};

main();

Create a new namespace

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

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

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

const namespace = {
    metadata: {
        name: 'test',
    },
};

const main = async () => {
    try {
        const createNamespaceRes = await k8sApi.createNamespace(namespace);
        console.log('New namespace created: ', createNamespaceRes.body);

        const readNamespaceRes = await k8sApi.readNamespace(namespace.metadata.name);
        console.log('Namespace: ', readNamespaceRes.body);

        await k8sApi.deleteNamespace(namespace.metadata.name, {});
    } catch (err) {
        console.error(err);
    }
};

main();

Create a cluster configuration programatically

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

const cluster = {
    name: 'my-server',
    server: 'http://server.com',
};

const user = {
    name: 'my-user',
    password: 'some-password',
};

const context = {
    name: 'my-context',
    user: user.name,
    cluster: cluster.name,
};

const kc = new k8s.KubeConfig();
kc.loadFromOptions({
    clusters: [cluster],
    users: [user],
    contexts: [context],
    currentContext: context.name,
});
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
...

Additional Examples and Documentation

There are several more JS and TS examples in the examples directory.

Documentation for the library is split into two resources:

  1. The Kubernetes API Reference is the source-of-truth for all Kubernetes client libraries, including this one. We suggest starting here!
  2. The Typedoc autogenerated docs can be viewed online and can also be built locally (see below)

Compatibility

Prior to the 0.13.0 release, release versions did not track Kubernetes versions. Starting with the 0.13.0 release, we will increment the minor version whenever we update the minor Kubernetes API version (e.g. 1.19.x) that this library is generated from.

Generally speaking newer clients will work with older Kubernetes, but compatability isn't 100% guaranteed.

client versionolder versions1.211.221.231.241.251.261.271.281.29
0.15.x-✓xxxxxxxx
0.16.x-+✓xxxxxxx
0.17.x-+++✓xxxxx
0.18.x--+++✓xxxx
0.19.x-----++✓xx
0.20.x------++✓x
0.21.x-------++✓

Key:

  • ✓ Exactly the same features / API objects in both javascript-client and the Kubernetes version.
  • + javascript-client has features or api objects that may not be present in the Kubernetes cluster, but everything they have in common will work.
  • - The Kubernetes cluster has features the javascript-client library can't use (additional API objects, etc).
  • x The Kubernetes cluster has no guarantees to support the API client of this version, as it only promises n-2 version support. It is not tested, and operations using API versions that have been deprecated and removed in later server versions won't function correctly.

Known Issues

  • Multiple kubeconfigs are not completely supported. Credentials are cached based on the kubeconfig username and these can collide across configs. Here is the related issue.
  • The client wasn't generated for Kubernetes 1.23 due to limited time from the maintainer(s)

Development

All dependencies of this project are expressed in its package.json file. Before you start developing, ensure that you have NPM installed, then run:

npm install

(re) Generating code

npm run generate

Documentation

Documentation is generated via typedoc:

npm run docs

To view the generated documentation, open docs/index.html

Formatting

Run npm run format or install an editor plugin like https://github.com/prettier/prettier-vscode and https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig

Linting

Run npm run lint or install an editor plugin like https://github.com/Microsoft/vscode-typescript-tslint-plugin

Testing

Tests are written using the Chai library. See config_test.ts for an example.

To run tests, execute the following:

npm test

Contributing

Please see CONTRIBUTING.md for instructions on how to contribute.

NPM DownloadsLast 30 Days