kubectl commands

73 commands, each with a one-line explanation. Click a command to copy it, or its title for details.

Commands 73 shown

  • kubectl get pods -A -o wide

    All pods with node placement and IPs

    pods

  • kubectl describe pod <name> -n <ns>

    Full details: events, conditions, volume mounts

    pods · debug

  • kubectl logs -f <pod> -n <ns>

    Stream logs in real time; add -c <container> for multi-container pods

    logs · debug

  • kubectl logs <pod> --previous -n <ns>

    Logs from the last crashed/restarted container instance

    logs · debug

  • kubectl exec -it <pod> -n <ns> -- bash

    Interactive shell inside a running container

    pods · debug

  • kubectl port-forward svc/<name> 8080:80 -n <ns>

    Tunnel a cluster service port to localhost

    debug · network

  • kubectl rollout status deployment/<name> -n <ns>

    Block until rollout completes or times out (use in CI)

    deployments

  • kubectl rollout undo deployment/<name> -n <ns>

    Revert to the previous revision

    deployments

  • kubectl scale deployment/<name> --replicas=3 -n <ns>

    Immediately change replica count

    deployments

  • kubectl get events -A --sort-by='.lastTimestamp'

    Recent cluster events, oldest first — great for post-incident review

    debug

  • kubectl apply --server-side --dry-run=server -f file.yaml

    Validate manifest against live API without applying changes

    config

  • kubectl get deployment/<name> -n <ns> -o yaml

    Current live state with managed fields stripped; useful as a base

    config

  • kubectl delete pod <name> -n <ns> --grace-period=0 --force

    Remove a Terminating pod immediately (use with caution)

    pods · debug

  • kubectl cp <ns>/<pod>:/remote/path ./local-path

    Extract a file from a running container

    debug

  • kubectl cordon <node>

    Mark node as unschedulable — no new pods land here

    nodes

  • kubectl drain <node> --ignore-daemonsets --delete-emptydir-data

    Gracefully evict all pods before maintenance

    nodes

  • kubectl edit deployment/<name> -n <ns>

    Open resource in $EDITOR; changes applied on save

    deployments · config

  • kubectl auth can-i list pods --as=system:serviceaccount:<ns>:<sa> -n <ns>

    Check what a ServiceAccount is allowed to do

    rbac · debug

  • kubectl get pods -n <ns> -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase'

    Print only the fields you care about without jq

    pods

  • kubectl patch deployment <name> -n <ns> -p '{"spec":{"replicas":2}}'

    Inline JSON patch without editing the whole manifest

    deployments · config

  • kubectl annotate pod <pod> -n <ns> key=value --overwrite

    Set or update an annotation; --overwrite replaces existing value

    config

  • kubectl label node <node> role=worker --overwrite

    Add or change a label on any resource

    nodes · config

  • kubectl taint nodes <node> key=value:NoSchedule

    Prevent pods without matching toleration from scheduling on node

    nodes

  • kubectl taint nodes <node> key=value:NoSchedule-

    Remove a taint by appending a dash at the end

    nodes

  • kubectl set image deployment/<name> <container>=image:tag -n <ns>

    Rolling-update the container image without editing YAML

    deployments

  • kubectl rollout history deployment/<name> -n <ns>

    Show all revisions with change cause (requires --record or annotations)

    deployments

  • kubectl rollout restart deployment/<name> -n <ns>

    Trigger zero-downtime pod rotation without changing spec

    deployments

  • kubectl create namespace <ns>

    Create a new namespace; idempotent with --dry-run=client | apply

    config

  • kubectl set resources deployment/<name> -c <container> --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=512Mi -n <ns>

    Update resource requests and limits on a running deployment

    deployments · config

  • kubectl run tmp --image=nicolaka/netshoot -it --rm --restart=Never -n <ns> -- bash

    Ephemeral pod for debugging; deleted on exit

    debug · pods

  • kubectl get nodes --show-labels

    See all labels assigned to each node

    nodes

  • kubectl uncordon <node>

    Re-enable scheduling on a previously cordoned node

    nodes

  • kubectl get hpa -A

    Horizontal Pod Autoscaler current/desired replicas and metrics

    deployments · monitoring

  • kubectl describe resourcequota -n <ns>

    Used vs hard limits for CPU, memory, object counts in namespace

    config

  • kubectl get pdb -A

    Show min-available and current healthy pod counts

    deployments

  • kubectl describe limitrange -n <ns>

    Default and max resource limits applied to pods in namespace

    config

  • kubectl get crds --sort-by='.metadata.creationTimestamp'

    List all Custom Resource Definitions sorted by creation time

    config · debug

  • kubectl get endpoints <svc> -n <ns>

    Show pod IPs backing a Service — diagnose selector mismatch

    network · debug

  • kubectl get certificate -A -o wide

    See cert-manager Certificate ready status and expiry dates

    network · debug

  • kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.topologySpreadConstraints}'

    Inspect topology spread constraints on a pod

    pods · config

  • kubectl apply -f ./dir/ --prune -l app=<label> -n <ns>

    Apply manifests and remove stale objects matching the label selector

    config

  • kubectl diff -f file.yaml

    Show what would change if you applied this manifest now

    config · debug

  • kubectl get pods -n <ns> -l app=<label> -o name | xargs -I{} kubectl exec {} -n <ns> -- <cmd>

    Run a command in every pod matching a label selector

    pods · debug

  • kubectl get pods -n <ns> -w

    Live-refresh pod list as statuses change

    pods · debug

  • kubectl top pods -A --sort-by=cpu

    CPU-sorted pod usage across all namespaces

    pods · monitoring

  • kubectl create token <sa-name> -n <ns> --duration=1h

    Generate a short-lived bound service account token

    rbac · config

  • kubectl auth can-i --list -n <ns>

    Show all permissions the current user has in a namespace

    rbac · debug

  • kubectl delete pods --all -n <ns>

    Force recreation of all pods — useful after ConfigMap changes

    pods

  • kubectl get ingress -A

    All Ingress resources with hosts and addresses

    network

  • kubectl get pods -n <ns> -o yaml > pods-dump.yaml

    Backup/inspect entire pod state in a namespace

    debug · pods

  • kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{range .spec.containers[*]}{.image}{"\n"}{end}{end}'

    Enumerate every container image running in the cluster

    debug · pods

  • kubectl config use-context <context>

    Switch the active cluster context

    config

  • kubectl config get-contexts

    Show all contexts in current kubeconfig

    config

  • KUBECONFIG=~/.kube/config:~/.kube/cluster2.yaml kubectl config view --flatten > ~/.kube/merged.yaml

    Combine multiple kubeconfig files into one

    config

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

    Avoid typing -n on every command for this context

    config

  • kubectl cluster-info

    Show API server and CoreDNS endpoints

    debug · config

  • kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{": "}{range .status.conditions[*]}{.type}={.status},{" "}{end}{"\n"}{end}'

    Show all conditions per node (Ready, MemoryPressure, DiskPressure)

    nodes · debug

  • kubectl create job --from=cronjob/<name> manual-run -n <ns>

    Immediately run a CronJob as a one-off Job

    config · debug

  • kubectl wait pod -l app=<label> -n <ns> --for=condition=Ready --timeout=120s

    Block until matching pods are Ready or timeout

    pods · config

  • kubectl get --raw /metrics | grep apiserver_request_total

    Pull raw Prometheus metrics from the apiserver without a metrics stack

    metrics · observability · performance

  • kubectl get --raw '/healthz/etcd?verbose'

    Verify etcd connectivity through the apiserver health endpoint

    etcd · troubleshooting · k8s

  • kubectl get --raw '/apis/metrics.k8s.io/v1beta1/nodes' | jq '.items[] | {name:.metadata.name, cpu:.usage.cpu, mem:.usage.memory}'

    Raw node usage from metrics API; bypasses kubectl top formatting

    metrics · monitoring · performance

  • kubectl debug <pod> -n <ns> --copy-to=<pod>-dbg --share-processes --image=nicolaka/netshoot -- sleep infinity

    Clone pod with a debug container sharing the PID namespace; original stays untouched

    debug · troubleshooting · k8s

  • kubectl explain deploy.spec --recursive | less

    Dump the full nested field tree of a resource spec; great for hunting valid fields

    k8s · troubleshooting

  • kubectl rollout pause deploy/<name> -n <ns>; kubectl rollout resume deploy/<name> -n <ns>

    Batch multiple edits without triggering rollouts, then resume to apply once

    gitops · k8s

  • kubectl apply view-last-applied deploy/<name> -n <ns> -o yaml

    Show the last-applied-configuration annotation; diff intent vs live state

    gitops · troubleshooting

  • kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp

    Cluster-wide Warning events newest last; fast triage of failing workloads

    troubleshooting · monitoring · debug

  • kubectl get pods -A --field-selector status.phase=Failed

    List pods in Failed phase across namespaces for cleanup or investigation

    troubleshooting · debug · k8s

  • kubectl wait --for=jsonpath='{.status.loadBalancer.ingress[0].ip}' svc/<name> -n <ns> --timeout=120s

    Block in CI until a Service gets its external IP; works on any jsonpath field

    ci · gitops · k8s

  • kubectl auth can-i list secrets -n <ns> --as=<name> --as-group=system:serviceaccounts

    Test RBAC as another identity without their kubeconfig; needs impersonate verb

    security · troubleshooting · k8s

  • kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\n"}{end}' | sort -k3 -rn | head

    Surface the most-restarting pods to catch crashloops fast

    troubleshooting · debug · monitoring

  • 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}'

    Show reserved overhead per node; gap = kube/system reservations

    performance · monitoring · k8s

  • 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>"}}}]'

    Build a CM from KEY=VALUE file, then JSON-patch it into a container's envFrom

    secrets · gitops · k8s