kubectl
2 min read

kubectl is the Kubernetes command-line tool that communicates with the Kubernetes API server to manage cluster resources such as pods, deployments, services, and more.

It supports imperative commands to create, update, and delete resources, as well as declarative workflows by applying YAML or JSON configuration files.

Common kubectl Commands

Cluster Information

• Get cluster info

bash
kubectl cluster-info

• Get cluster nodes

bash
kubectl get nodes

Working with Pods

• List all pods in default namespace

bash
kubectl get pods

• Get detailed info about a pod

bash
kubectl describe pod <pod-name>

• Create a pod from a YAML file

bash
kubectl apply -f pod.yaml

• Delete a pod

bash
kubectl delete pod <pod-name>

• View logs from a pod

bash
kubectl logs <pod-name>

Managing Deployments

• List deployments

bash
kubectl get deployments

• Create/update deployment from YAML

bash
kubectl apply -f deployment.yaml

• Scale a deployment

bash
kubectl scale deployment/<deployment-name> --replicas=3

• Rollout status

bash
kubectl rollout status deployment/<deployment-name>

Services

• List services

bash
kubectl get svc

• Create a service from YAML

bash
kubectl apply -f service.yaml

• Expose deployment as a service

bash
kubectl expose deployment <deployment-name> --type=LoadBalancer --port=80

Namespaces

• List namespaces

bash
kubectl get namespaces

• Set namespace for current context

bash
kubectl config set-context --current --namespace=<namespace>

Configuration and Context

• View current context

bash
kubectl config current-context

• List contexts

bash
kubectl config get-contexts

• Switch context

bash
kubectl config use-context <context-name>



Advanced Usage

Labeling and Selecting

• Add a label to a resource

bash
kubectl label pods <pod-name> env=prod

• Select resources by label

bash
kubectl get pods -l env=prod

Port Forwarding

Forward a local port to a pod’s port:

bash
kubectl port-forward pod/<pod-name> 8080:80

Rolling Updates and Rollbacks

• Rollout update deployment

bash
kubectl rollout restart deployment/<deployment-name>

• Rollback to previous revision

bash
kubectl rollout undo deployment/<deployment-name>

Debugging

• Execute a command inside a pod

bash
kubectl exec -it <pod-name> -- /bin/bash

• Describe a resource to get detailed info and events

bash
kubectl describe <resource> <name>

• Remove stuck finalizers

bash
kubectl patch <resource> <name> -n <namespace> -p '{"metadata":{"finalizers":[]}}' --type=merge