kubectl

73 commands

73 shown

List all pods across namespaces All pods with node placement and IPs kubectl get pods -A -o wide #pods Describe a pod Full details: events, conditions, volume mounts kubectl describe pod <name> -n <ns> #pods#debug Follow pod logs Stream logs in real time; add -c <container> for multi-container pods kubectl logs -f <pod> -n <ns> #logs#debug Logs from previous container Logs from the last crashed/restarted container instance kubectl logs <pod> --previous -n <ns> #logs#debug Exec into pod Interactive shell inside a running container kubectl exec -it <pod> -n <ns> -- bash #pods#debug Port-forward a service Tunnel a cluster service port to localhost kubectl port-forward svc/<name> 8080:80 -n <ns> #debug#network Watch rollout status Block until rollout completes or times out (use in CI) kubectl rollout status deployment/<name> -n <ns> #deployments Rollback deployment Revert to the previous revision kubectl rollout undo deployment/<name> -n <ns> #deployments Scale deployment Immediately change replica count kubectl scale deployment/<name> --replicas=3 -n <ns> #deployments Get events sorted by time Recent cluster events, oldest first — great for post-incident review kubectl get events -A --sort-by='.lastTimestamp' #debug Server-side dry-run Validate manifest against live API without applying changes kubectl apply --server-side --dry-run=server -f file.yaml #config Export live resource as YAML Current live state with managed fields stripped; useful as a base kubectl get deployment/<name> -n <ns> -o yaml #config Force delete stuck pod Remove a Terminating pod immediately (use with caution) kubectl delete pod <name> -n <ns> --grace-period=0 --force #pods#debug Copy file from pod Extract a file from a running container kubectl cp <ns>/<pod>:/remote/path ./local-path #debug Cordon a node Mark node as unschedulable — no new pods land here kubectl cordon <node> #nodes Drain a node Gracefully evict all pods before maintenance kubectl drain <node> --ignore-daemonsets --delete-emptydir-data #nodes Edit a live resource Open resource in $EDITOR; changes applied on save kubectl edit deployment/<name> -n <ns> #deployments#config Verify RBAC permissions Check what a ServiceAccount is allowed to do kubectl auth can-i list pods --as=system:serviceaccount:<ns>:<sa> -n <ns> #rbac#debug Get resource with custom columns Print only the fields you care about without jq kubectl get pods -n <ns> -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase' #pods Patch resource field Inline JSON patch without editing the whole manifest kubectl patch deployment <name> -n <ns> -p '{"spec":{"replicas":2}}' #deployments#config Annotate resource Set or update an annotation; --overwrite replaces existing value kubectl annotate pod <pod> -n <ns> key=value --overwrite #config Label resource Add or change a label on any resource kubectl label node <node> role=worker --overwrite #nodes#config Add taint to node Prevent pods without matching toleration from scheduling on node kubectl taint nodes <node> key=value:NoSchedule #nodes Remove taint from node Remove a taint by appending a dash at the end kubectl taint nodes <node> key=value:NoSchedule- #nodes Set image on deployment Rolling-update the container image without editing YAML kubectl set image deployment/<name> <container>=image:tag -n <ns> #deployments List rollout history Show all revisions with change cause (requires --record or annotations) kubectl rollout history deployment/<name> -n <ns> #deployments Restart deployment (rolling) Trigger zero-downtime pod rotation without changing spec kubectl rollout restart deployment/<name> -n <ns> #deployments Create namespace Create a new namespace; idempotent with --dry-run=client | apply kubectl create namespace <ns> #config Set resource requests/limits Update resource requests and limits on a running deployment kubectl set resources deployment/<name> -c <container> --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=512Mi -n <ns> #deployments#config Run one-off pod Ephemeral pod for debugging; deleted on exit kubectl run tmp --image=nicolaka/netshoot -it --rm --restart=Never -n <ns> -- bash #debug#pods Get node labels See all labels assigned to each node kubectl get nodes --show-labels #nodes Uncordon a node Re-enable scheduling on a previously cordoned node kubectl uncordon <node> #nodes Get HPA status Horizontal Pod Autoscaler current/desired replicas and metrics kubectl get hpa -A #deployments#monitoring View resource quotas Used vs hard limits for CPU, memory, object counts in namespace kubectl describe resourcequota -n <ns> #config Get PodDisruptionBudget Show min-available and current healthy pod counts kubectl get pdb -A #deployments View LimitRange Default and max resource limits applied to pods in namespace kubectl describe limitrange -n <ns> #config Get all CRDs List all Custom Resource Definitions sorted by creation time kubectl get crds --sort-by='.metadata.creationTimestamp' #config#debug Get service endpoints Show pod IPs backing a Service — diagnose selector mismatch kubectl get endpoints <svc> -n <ns> #network#debug Check certificate expiry (cert-manager) See cert-manager Certificate ready status and expiry dates kubectl get certificate -A -o wide #network#debug View pod topology spread Inspect topology spread constraints on a pod kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.topologySpreadConstraints}' #pods#config Apply with prune Apply manifests and remove stale objects matching the label selector kubectl apply -f ./dir/ --prune -l app=<label> -n <ns> #config Diff live vs local Show what would change if you applied this manifest now kubectl diff -f file.yaml #config#debug Exec command in all pods Run a command in every pod matching a label selector kubectl get pods -n <ns> -l app=<label> -o name | xargs -I{} kubectl exec {} -n <ns> -- <cmd> #pods#debug Watch pod status changes Live-refresh pod list as statuses change kubectl get pods -n <ns> -w #pods#debug Top pods by CPU CPU-sorted pod usage across all namespaces kubectl top pods -A --sort-by=cpu #pods#monitoring Create ServiceAccount token Generate a short-lived bound service account token kubectl create token <sa-name> -n <ns> --duration=1h #rbac#config Check who can do what (audit) Show all permissions the current user has in a namespace kubectl auth can-i --list -n <ns> #rbac#debug Delete all pods in namespace Force recreation of all pods — useful after ConfigMap changes kubectl delete pods --all -n <ns> #pods Get ingress list All Ingress resources with hosts and addresses kubectl get ingress -A #network Dump all pod YAML to file Backup/inspect entire pod state in a namespace kubectl get pods -n <ns> -o yaml > pods-dump.yaml #debug#pods Jsonpath — all container images Enumerate every container image running in the cluster kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' #debug#pods Switch kubeconfig context Switch the active cluster context kubectl config use-context <context> #config List kubeconfig contexts Show all contexts in current kubeconfig kubectl config get-contexts #config Merge kubeconfigs Combine multiple kubeconfig files into one KUBECONFIG=~/.kube/config:~/.kube/cluster2.yaml kubectl config view --flatten > ~/.kube/merged.yaml #config Set default namespace for context Avoid typing -n on every command for this context kubectl config set-context --current --namespace=<ns> #config Get cluster info Show API server and CoreDNS endpoints kubectl cluster-info #debug#config Get node conditions Show all conditions per node (Ready, MemoryPressure, DiskPressure) kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{": "}{range .status.conditions[*]}{.type}={.status},{" "}{end}{"\n"}{end}' #nodes#debug Trigger CronJob manually Immediately run a CronJob as a one-off Job kubectl create job --from=cronjob/<name> manual-run -n <ns> #config#debug Wait for pod ready Block until matching pods are Ready or timeout kubectl wait pod -l app=<label> -n <ns> --for=condition=Ready --timeout=120s #pods#config Scrape apiserver metrics endpoint Pull raw Prometheus metrics from the apiserver without a metrics stack kubectl get --raw /metrics | grep apiserver_request_total #kubectl#metrics#observability#performance Check etcd health via apiserver Verify etcd connectivity through the apiserver health endpoint kubectl get --raw '/healthz/etcd?verbose' #kubectl#etcd#troubleshooting#k8s Node metrics from metrics.k8s.io API Raw node usage from metrics API; bypasses kubectl top formatting kubectl get --raw '/apis/metrics.k8s.io/v1beta1/nodes' | jq '.items[] | {name:.metadata.name, cpu:.usage.cpu, mem:.usage.memory}' #kubectl#metrics#monitoring#performance Ephemeral debug copy with shared PIDs Clone pod with a debug container sharing the PID namespace; original stays untouched kubectl debug <pod> -n <ns> --copy-to=<pod>-dbg --share-processes --image=nicolaka/netshoot -- sleep infinity #kubectl#debug#troubleshooting#k8s Explain deployment spec recursively Dump the full nested field tree of a resource spec; great for hunting valid fields kubectl explain deploy.spec --recursive | less #kubectl#k8s#troubleshooting Pause and resume a rollout Batch multiple edits without triggering rollouts, then resume to apply once kubectl rollout pause deploy/<name> -n <ns>; kubectl rollout resume deploy/<name> -n <ns> #kubectl#gitops#k8s View last applied configuration Show the last-applied-configuration annotation; diff intent vs live state kubectl apply view-last-applied deploy/<name> -n <ns> -o yaml #kubectl#gitops#troubleshooting Warning events across all namespaces Cluster-wide Warning events newest last; fast triage of failing workloads kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp #kubectl#troubleshooting#monitoring#debug Find all failed pods cluster-wide List pods in Failed phase across namespaces for cleanup or investigation kubectl get pods -A --field-selector status.phase=Failed #kubectl#troubleshooting#debug#k8s Wait on a jsonpath condition Block in CI until a Service gets its external IP; works on any jsonpath field kubectl wait --for=jsonpath='{.status.loadBalancer.ingress[0].ip}' svc/<name> -n <ns> --timeout=120s #kubectl#ci#gitops#k8s Impersonate a user and group Test RBAC as another identity without their kubeconfig; needs impersonate verb kubectl auth can-i list secrets -n <ns> --as=<name> --as-group=system:serviceaccounts #kubectl#security#troubleshooting#k8s Sort pods by container restart count Surface the most-restarting pods to catch crashloops fast kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\n"}{end}' | sort -k3 -rn | head #kubectl#troubleshooting#debug#monitoring Compare node allocatable vs capacity Show reserved overhead per node; gap = kube/system reservations kubectl get nodes -o json | jq -r '.items[] | {node:.metadata.name, capCPU:.status.capacity.cpu, allocCPU:.status.allocatable.cpu, capMem:.status.capacity.memory, allocMem:.status.allocatable.memory}' #kubectl#performance#monitoring#k8s ConfigMap from env-file with patch op Build a CM from KEY=VALUE file, then JSON-patch it into a container's envFrom kubectl create configmap <name> --from-env-file=app.env -n <ns> --dry-run=client -o yaml | kubectl apply -f -; kubectl patch deploy/<name> -n <ns> --type=json -p='[{"op":"add","path":"/spec/template/spec/containers/0/envFrom/-","value":{"configMapRef":{"name":"<name>"}}}]' #kubectl#secrets#gitops#k8s
no commands match