Kubectl Example

Kubectl Example

Cluster, Kubeconfig, Contexts

  • Get the cluster information
kubectl cluster-info
  • Get cluster configs
kubectl config view # Sensitive data masked
kubectl config view --raw=true # Show sensitive data also
  • List all the contexts in kubeconfig
kubectl config get-contexts
  • Use a specific context
kubectl config use-context <CONTEXT_NAME>


Namespaces

  • Get namespaces
kubectl get namespaces
  • Create a new namespace
kubectl create namespace <NAMESPACE_NAME>
  • Change default namespace for the context
kubectl config set-context --current --namespace=<NAMESPACE_NAME>
  • Delete namespace
kubectl delete namespace <NAMESPACE_NAME>
  • Describe a namespace
kubectl describe namespace <NAMESPACE_NAME>
  • Show resource usage of a namespace
kubectl top namespace <NAMESPACE_NAME>


Nodes, Pods

  • Get Cluster nodes status
kubectl get nodes
  • Get resource status for given node name
kubectl top nodes
kubectl top node <NODE_NAME>
  • Detailed resource allocation per node
kubectl describe nodes | grep Allocated -A 5
  • Pods running on a particular node
kubectl get pods -o wide | grep <NODE_NAME>
  • Add a label to a node
kubectl label nodes <NODE_NAME> <LABEL_NAME>
kubectl label nodes worker0 nodename=worker-node-0


Port-forward, Logs, Describe and others

  • Apply a new k8s object(s) meaning used for creating and updating resource based definition provided in JSON/YAML
kubectl apply -f <filename.yaml>
  • Port forward to a particular deploy/pod/sts
kubectl port-forward <POD/NAME> <LOCAL_PORT>:<REMOTE_PORT> # Pods
# or
kubectl port-forward deployment/<DEPLOYMENT_NAME> <LOCAL_PORT>:<REMOTE_PORT> # Deployments
kubectl port-forward sts/<STS_NAME> <LOCAL_PORT>:<REMOTE_PORT> # Statefulsets
  • Logs to a particular deploy/pod/sts
kubectl logs <POD/NAME> <LOCAL_PORT>:<REMOTE_PORT> # Pods
kubectl logs -f <POD/NAME> <LOCAL_PORT>:<REMOTE_PORT> # Pods, and real-time tailing of the logs
# or
kubectl logs deployment/<DEPLOYMENT_NAME> <LOCAL_PORT>:<REMOTE_PORT> # Deployments
kubectl logs sts/<STS_NAME> <LOCAL_PORT>:<REMOTE_PORT> # Statefulsets
  • Describe a k8s object
kubectl describe <K8S_OBJECT> <OBJET_NAME>
# Eg:
kubectl describe secrets my-secrets
  • List all the events occurring in the cluster
kubectl get events
  • Run a BusyBox/Alpine debug pod for network/connectivity troubleshooting. This helps verify whether service endpoints are functioning correctly and if traffic is being redirected to the intended destination pod.
kubectl run -i -t debug --image=busybox --restart=Never # Start an interactive shell for debugging
kubectl run debug --image=busybox --command -- sleep 9999 # Run a background pod in the default namespace;
kubectl run debug --image=alpine --restart=Never --command -- sleep 9999 # Run a background pod with Alpine Linux; it stays active and restarts after the sleep