kubectl

kubectl is the command-line interface (CLI) for Kubernetes. It manages resources in the cluster (Pods, Deployments, Services, ConfigMaps, etc.) through the API Server, interacting directly with the Kubernetes API. It reads the ~/.kube/config file to configure the connection to the target cluster. In essence it is a REST client that sends HTTP requests to the Kubernetes API.

Reference docs: kubectl reference (official)

2. Basic Syntax

kubectl [command] [TYPE] [NAME] [flags]
PartDescription
commandOperation type, e.g. get, create, delete, describe
TYPEResource type, e.g. pod, deployment, service (abbreviations supported)
NAMEResource name (optional)
flagsParameters, e.g. -n namespace, -o yaml

✅ Examples:

kubectl get pods -A                   # List all Pods
kubectl describe node node1        # Show details of node1
kubectl delete deployment my-app   # Delete the Deployment named my-app

3. Common Commands Cheat Sheet

CommandPurposeExample
kubectl getList resourceskubectl get pods -A
kubectl describeShow detailed resource infokubectl describe pod nginx-123
kubectl createCreate a resource from a file or stdinkubectl create -f app.yaml
kubectl applyDeclarative update (recommended)kubectl apply -f app.yaml
kubectl deleteDelete a resourcekubectl delete pod nginx-123
kubectl logsView container logskubectl logs -f my-pod
kubectl execRun a command inside a containerkubectl exec -it my-pod -- sh
kubectl port-forwardPort-forward (access a service locally)kubectl port-forward svc/my-svc 8080:80
kubectl proxyStart the API proxykubectl proxy --port=8001
kubectl topShow resource usage (requires Metrics Server)kubectl top nodes
kubectl rolloutManage rollouts / rollback / statuskubectl rollout undo deploy/my-app

4. Common Resource Types

Full nameAbbrev.Description
podspoSmallest scheduling unit
servicessvcService discovery & load balancing
deploymentsdeployStateless app management
daemonsetsdsOne Pod per node (e.g. Flannel)
statefulsetsstsStateful apps (e.g. databases)
configmapscmNon-sensitive config data
secretssecretSensitive data (base64 encoded)
namespacesnsNamespace (logical isolation)
nodesnoWorker node
persistentvolumespvStorage volume (cluster-scoped)
persistentvolumeclaimspvcStorage claim (namespace-scoped)

✅ Use abbreviations to work faster: kubectl get po instead of kubectl get pods

5. Common Flags

FlagDescription
-n <namespace>Target a namespace (default default)
-A / --all-namespacesAll namespaces
-o wideShow more info (IP, Node, etc.)
-o yaml / -o jsonOutput as YAML/JSON
-l key=valueFilter resources by label
-wWatch in real time
--dry-run=clientDry run (no actual creation)
--forceForce delete (with --grace-period=0)

✅ Examples:

# Show IP and node for every Pod in kube-system
kubectl get pods -n kube-system -o wide

# Watch Pod changes in the default namespace in real time
kubectl get pods -w

6. Typical Usage Scenarios

1. Troubleshooting a Pod

kubectl get pods                          # Check status
kubectl describe pod <pod-name>           # Inspect events and config
kubectl logs <pod-name>                   # View logs
kubectl exec -it <pod-name> -- sh         # Enter the container

2. Deploying an Application

kubectl apply -f deployment.yaml          # Deploy
kubectl get deploy                        # Check deployment status
kubectl rollout status deploy/my-app      # Check rollout status

3. Debugging a Service

# Forward local port 8080 to the Service's port 80
kubectl port-forward svc/my-service 8080:80

# Test whether it is reachable
curl http://localhost:8080

4. Checking Cluster Status

kubectl get nodes                         # Are nodes Ready?
kubectl top nodes                         # CPU/memory usage (needs Metrics Server)

7. Config File: ~/.kube/config

  • Contains cluster, user, and context information.
  • Manage it with these commands:
kubectl config view                # View current config
kubectl config use-context prod    # Switch context
kubectl config get-contexts        # List all contexts

This file is critical when managing multiple clusters.

8. Advanced Tips

1. Shell Auto-Completion (Bash/Zsh)

# Bash
echo "source <(kubectl completion bash)" >> ~/.bashrc
source ~/.bashrc

# Zsh
echo "source <(kubectl completion zsh)" >> ~/.zshrc

2. Aliases

alias k=kubectl
alias kg='kubectl get'
alias kd='kubectl describe'

3. Custom Output Columns

kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase

4. Bulk Deletion

# Delete all Jobs in Completed state
kubectl delete job -l job-name=my-job

# Delete all Pods that are not Running
kubectl delete pod --field-selector=status.phase!=Running

9. Caveats

  1. Access control: Operations are restricted by RBAC; ordinary users may be unable to delete system Pods.
  2. Namespace isolation: When -n is omitted, the default namespace is targeted.
  3. apply vs create:
    • apply: declarative, supports incremental updates (recommended).
    • create: imperative, re-running it errors out.
  4. Deleting resources: Some resources (e.g. PVC) persist after the Pod is deleted and must be cleaned up manually.

10. Learning Resources

Summary

kubectl is the “Swiss Army knife” of Kubernetes:

  • Inspect: get, describe, logs
  • Operate: apply, delete, exec
  • Debug: port-forward, proxy, top
  • Manage: config, rollout, scale

Master kubectl, and you master the lifeblood of Kubernetes!