Kubernetes provides a powerful REST API for managing containers, deployments, services, and more. Every kubectl command is just an API call — and you can use it directly.
API Access
# Start a proxy to the API server
kubectl proxy --port=8001
# List pods
curl http://localhost:8001/api/v1/namespaces/default/pods | jq .items[].metadata.name
# Get deployments
curl http://localhost:8001/apis/apps/v1/namespaces/default/deployments
Node.js Client
npm install @kubernetes/client-node
import * as k8s from "@kubernetes/client-node";
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
const appsApi = kc.makeApiClient(k8s.AppsV1Api);
// List pods
const { body } = await k8sApi.listNamespacedPod("default");
body.items.forEach(pod => {
console.log(`${pod.metadata.name}: ${pod.status.phase}`);
});
Create a Deployment
const deployment = {
metadata: { name: "my-app" },
spec: {
replicas: 3,
selector: { matchLabels: { app: "my-app" } },
template: {
metadata: { labels: { app: "my-app" } },
spec: {
containers: [{
name: "app",
image: "nginx:latest",
ports: [{ containerPort: 80 }],
resources: {
requests: { cpu: "100m", memory: "128Mi" },
limits: { cpu: "500m", memory: "256Mi" }
}
}]
}
}
}
};
await appsApi.createNamespacedDeployment("default", deployment);
console.log("Deployment created!");
Watch for Changes
const watch = new k8s.Watch(kc);
await watch.watch("/api/v1/namespaces/default/pods", {},
(type, pod) => {
console.log(`${type}: ${pod.metadata.name} — ${pod.status.phase}`);
},
(err) => console.error(err)
);
Scale Deployment
const scale = { spec: { replicas: 5 } };
await appsApi.patchNamespacedDeploymentScale(
"my-app", "default", scale,
undefined, undefined, undefined, undefined,
{ headers: { "Content-Type": "application/merge-patch+json" } }
);
kubectl Essentials
kubectl get pods -o wide
kubectl describe pod my-pod
kubectl logs my-pod --tail=100 -f
kubectl exec -it my-pod -- /bin/sh
kubectl port-forward svc/my-service 8080:80
kubectl apply -f deployment.yaml
kubectl rollout restart deployment/my-app
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)