kubectl

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

    kubectl cluster-info
  • Get cluster nodes

    kubectl get nodes

Working with Pods

  • List all pods in default namespace

    kubectl get pods
  • Get detailed info about a pod

    kubectl describe pod <pod-name>
  • Create a pod from a YAML file

    kubectl apply -f pod.yaml
  • Delete a pod

    kubectl delete pod <pod-name>
  • View logs from a pod

    kubectl logs <pod-name>

Managing Deployments

  • List deployments

    kubectl get deployments
  • Create/update deployment from YAML

    kubectl apply -f deployment.yaml
  • Scale a deployment

    kubectl scale deployment/<deployment-name> --replicas=3
  • Rollout status

    kubectl rollout status deployment/<deployment-name>

Services

  • List services

    kubectl get svc
  • Create a service from YAML

    kubectl apply -f service.yaml
  • Expose deployment as a service

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

Namespaces

  • List namespaces

    kubectl get namespaces
  • Set namespace for current context

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

Configuration and Context

  • View current context

    kubectl config current-context
  • List contexts

    kubectl config get-contexts
  • Switch context

    kubectl config use-context <context-name>

Advanced Usage

Labeling and Selecting

  • Add a label to a resource

    kubectl label pods <pod-name> env=prod
  • Select resources by label

    kubectl get pods -l env=prod

Port Forwarding

Forward a local port to a pod’s port:

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

Rolling Updates and Rollbacks

  • Rollout update deployment

    kubectl rollout restart deployment/<deployment-name>
  • Rollback to previous revision

    kubectl rollout undo deployment/<deployment-name>

Debugging

  • Execute a command inside a pod

    kubectl exec -it <pod-name> -- /bin/bash
  • Describe a resource to get detailed info and events

    kubectl describe <resource> <name>
  • Remove stuck finalizers

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