kubectl --helpDisplays the root level help menu for kubectl commands and global flags.
The Kubernetes command line: inspect and manage clusters, workloads, RBAC and secrets — and check what an identity is allowed to do.
sudo snap install kubectl --classickubectl versionPrints the client and server version information in JSON format.
Example
kubectl version --output=jsonkubectl cluster-infoDisplays addresses of the master and services, or dumps detailed cluster debugging info.
Example
kubectl cluster-info dumpkubectl api-resourcesLists all supported API resources available on the server, filtered by namespaced scope.
Example
kubectl api-resources --namespaced=truekubectl api-versionsLists the API versions that are supported by the current Kubernetes cluster.
kubectl config viewDisplays the current kubeconfig settings, optionally minimizing output to the current context.
Example
kubectl config view --minifykubectl config get-contextsLists all contexts defined in the kubeconfig file and highlights the active one.
kubectl config use-contextSwitches the current active context to the specified context name.
Example
kubectl config use-context my-cluster-contextkubectl config set-contextModifies the current context to set a default namespace for future commands.
Example
kubectl config set-context --current --namespace=devkubectl config delete-contextRemoves the specified context entry from the kubeconfig file.
Example
kubectl config delete-context old-clusterkubectl get namespacesLists all namespaces in the cluster along with their associated labels.
Example
kubectl get ns --show-labelskubectl create namespaceGenerates the YAML manifest for a new namespace without actually creating it.
Example
kubectl create namespace production --dry-run=client -o yamlkubectl get allLists most resources (pods, services, deployments) across every namespace in the cluster.
Example
kubectl get all --all-namespaceskubectl get podsLists pods with extended information such as IP address and Node assignment.
Example
kubectl get pods -o widekubectl get servicesLists services sorted alphabetically by their name.
Example
kubectl get svc --sort-by=.metadata.namekubectl runCreates a single pod instance imperatively using the specified image.
Example
kubectl run nginx --image=nginx --restart=Neverkubectl create deploymentCreates a deployment with a specified replica count and image.
Example
kubectl create deployment web --image=nginx --replicas=3kubectl exposeExposes a resource as a new Kubernetes Service.
Example
kubectl expose deployment web --port=80 --target-port=8080 --type=LoadBalancerkubectl create jobCreates a Job resource that runs a specific command to completion.
Example
kubectl create job manual-job --image=busybox -- datekubectl create cronjobCreates a CronJob that runs on a specific schedule.
Example
kubectl create cronjob my-cron --image=busybox --schedule="*/1 * * * *" -- datekubectl logsPrint the logs for a container in a pod or specified resource.
Example
kubectl logs my-podkubectl logs (follow)Streams the logs for a container in real-time, similar to tail -f.
Example
kubectl logs -f my-podkubectl logs (multi-container)Retrieves logs from a specific container within a multi-container pod.
Example
kubectl logs my-pod -c sidecar-containerkubectl logs (previous)Retrieves logs from a previous instantiation of a container (e.g., after a crash).
Example
kubectl logs my-pod --previouskubectl execExecutes a command inside a container with an interactive TTY.
Example
kubectl exec -it my-pod -- /bin/bashkubectl cpCopies files and directories to and from containers.
Example
kubectl cp /local/path my-pod:/container/pathkubectl port-forwardForwards one or more local ports to a pod.
Example
kubectl port-forward pod/my-pod 8080:80kubectl attachAttaches to a running process in a container to view output or interact.
Example
kubectl attach my-pod -c main-app -i -tkubectl top podDisplays current CPU and memory usage for pods and their containers.
Example
kubectl top pod --containerskubectl top nodeDisplays current CPU and memory usage for nodes.
kubectl applyApply a configuration to a resource by filename or directory.
Example
kubectl apply -f ./manifests/kubectl apply (server-side)Uses server-side apply to manage field ownership and merge conflicts.
Example
kubectl apply -f deployment.yaml --server-sidekubectl deleteDelete resources defined in a configuration file.
Example
kubectl delete -f deployment.yamlkubectl diffDisplays differences between the current live cluster state and the local manifest.
Example
kubectl diff -f deployment.yamlkubectl replaceReplaces a resource by filename, optionally forcing deletion and recreation.
Example
kubectl replace -f pod.yaml --forcekubectl kustomizeBuilds a kustomization target and prints the resulting YAML to stdout.
Example
kubectl kustomize ./overlays/productionkubectl explainDescribes the fields and structure of a Kubernetes resource type.
Example
kubectl explain deployment.spec.strategykubectl scaleUpdates the replica count of a deployment, replicaset, or statefulset.
Example
kubectl scale deployment/web --replicas=5kubectl autoscaleCreates a HorizontalPodAutoscaler to automatically manage scale.
Example
kubectl autoscale deployment/web --min=2 --max=10 --cpu-percent=80kubectl rollout statusWatches the status of a rollout until it is complete.
Example
kubectl rollout status daemonset/agentkubectl rollout historyViews the revision history of a rollout.
Example
kubectl rollout history deployment/web --revision=2kubectl rollout undoRolls back a deployment to a previous revision.
Example
kubectl rollout undo deployment/web --to-revision=1kubectl rollout restartRestarts a resource, triggering a new rollout without configuration changes.
Example
kubectl rollout restart deployment/webkubectl rollout pausePauses a rollout to perform multiple changes before resuming.
Example
kubectl rollout pause deployment/webkubectl rollout resumeResumes a paused rollout.
Example
kubectl rollout resume deployment/webkubectl create configmapCreates a ConfigMap from a file, directory, or literal value.
Example
kubectl create configmap app-config --from-file=config.propertieskubectl create secret genericCreates a generic secret from literal values or files.
Example
kubectl create secret generic db-pass --from-literal=password=safekubectl create secret docker-registryCreates a secret for authenticating with a Docker registry.
Example
kubectl create secret docker-registry regcred --docker-server=x --docker-username=user --docker-password=passkubectl create secret tlsCreates a TLS secret from a certificate and key file.
Example
kubectl create secret tls tls-secret --cert=path/to/cert.crt --key=path/to/key.keykubectl labelUpdates the labels on a resource, optionally overwriting existing ones.
Example
kubectl label pods my-pod environment=production --overwritekubectl annotateUpdates the annotations on a resource.
Example
kubectl annotate service my-service description="Load Balancer" --recordkubectl set imageUpdates the image of a container in a pod template.
Example
kubectl set image deployment/web nginx=nginx:1.19kubectl set envUpdates environment variables on a pod template.
Example
kubectl set env deployment/registry STORAGE_DIR=/localkubectl set resourcesSpecifies compute resource requirements for a container.
Example
kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mikubectl editEdit a resource on the server using the default text editor.
Example
kubectl edit svc/my-servicekubectl patch (merge)Update field(s) of a resource using strategic merge patch.
Example
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'kubectl patch (json)Update resource using RFC 6902 JSON patch.
Example
kubectl patch deployment web --type='json' -p='[{"op": "replace", "path": "/spec/replicas", "value": 3}]'kubectl cordonMark node as unschedulable to prevent new pods from arriving.
Example
kubectl cordon node-1kubectl uncordonMark node as schedulable, allowing new pods to start.
Example
kubectl uncordon node-1kubectl drainPrepare node for maintenance by evicting all pods.
Example
kubectl drain node-1 --ignore-daemonsets --delete-emptydir-datakubectl taintUpdate the taints on one or more nodes.
Example
kubectl taint nodes node1 key=value:NoSchedulekubectl get -o wideOutput in plain text with additional columns (e.g., Node, IP).
Example
kubectl get pods -o widekubectl get -o yamlOutput the full resource definition in YAML format.
Example
kubectl get pod my-pod -o yamlkubectl get -o jsonOutput the full resource definition in JSON format.
Example
kubectl get pod my-pod -o jsonkubectl get --show-labelsInclude a column showing labels attached to resources.
Example
kubectl get pods --show-labelskubectl get --sort-bySort list output by a specific JSONPath expression.
Example
kubectl get pods --sort-by=.status.startTimekubectl get -o jsonpath (names)Extract and print specific fields using a JSONPath expression.
Example
kubectl get pods -o jsonpath='{.items[*].metadata.name}'kubectl get -o custom-columnsDefine custom table columns based on field paths.
Example
kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].imagekubectl get --no-headersSuppress the header row in output, useful for scripts.
Example
kubectl get pods --no-headerskubectl get -l (label selector)Filter resources by label selector equality or set-based requirements.
Example
kubectl get pods -l app=nginx,tier=frontendkubectl get --field-selectorFilter resources based on the value of resource fields.
Example
kubectl get pods --field-selector status.phase=Runningkubectl create serviceaccountCreates a new ServiceAccount in the current namespace.
Example
kubectl create serviceaccount my-sakubectl create roleCreates a Role with specific permissions within a namespace.
Example
kubectl create role pod-reader --verb=get,list --resource=podskubectl create rolebindingBinds a Role to a user or group in a specific namespace.
Example
kubectl create rolebinding read-pods --role=pod-reader --user=janekubectl create clusterroleCreates a ClusterRole with permissions across the entire cluster.
Example
kubectl create clusterrole node-reader --verb=get,list --resource=nodeskubectl create clusterrolebindingBinds a ClusterRole to a user or group globally.
Example
kubectl create clusterrolebinding read-nodes-global --clusterrole=node-reader --group=system:authenticatedkubectl auth can-iChecks if the current user has permission to perform an action.
Example
kubectl auth can-i create podskubectl auth can-i (impersonate)Checks permissions impersonating another user or group.
Example
kubectl auth can-i list secrets --as=jane --as-group=devskubectl auth reconcilePatches RBAC roles and bindings to match the input file if safe.
Example
kubectl auth reconcile -f rbac-policy.yamlkubectl certificate approveApproves a CertificateSigningRequest (CSR).
Example
kubectl certificate approve my-csrkubectl certificate denyDenies a CertificateSigningRequest (CSR).
Example
kubectl certificate deny my-csrkubectl debug (node)Creates a debugging pod on a node to troubleshoot host issues.
Example
kubectl debug node/worker-1 -it --image=busyboxkubectl debug (pod)Attaches a new container to a running pod for debugging purposes.
Example
kubectl debug -it pod/my-pod --image=busybox --target=app-containerkubectl alpha eventsExperimental command to view events filtered for a specific object.
Example
kubectl alpha events --for=pod/nginxkubectl plugin listLists all available kubectl plugins installed in the path.
kubectl delete nodeRemoves a node object from the cluster (does not terminate VM).
Example
kubectl delete node worker-1kubectl delete pods (force)Forcefully deletes a pod, bypassing graceful termination.
Example
kubectl delete pod my-pod --grace-period=0 --forcekubectl delete evictionsDeletes all failed pods across all namespaces (common cleanup task).
Example
kubectl delete pod --field-selector=status.phase=Failed -Akubectl get pod (security context)Audits the security context of running pods to find misconfigurations.
Example
kubectl get pods -o jsonpath='{.items[*].spec.securityContext}'kubectl get pspLists PodSecurityPolicies (if enabled) to verify admission controls.
kubectl get networkpoliciesAudits network segmentation rules across the cluster.
Example
kubectl get networkpolicies --all-namespaceskubectl get clusterrolebindings (audit)Audits global permissions to identify privileged users.
Example
kubectl get clusterrolebindings -o custom-columns=NAME:.metadata.name,ROLE:.roleRef.name,SUBJECT:.subjects[*].namekubectl get pods (by time)Lists pods ordered by creation time to identify recently launched rogue containers.
Example
kubectl get pods --sort-by=.metadata.creationTimestampkubectl get secrets (audit)Lists secrets and their types to audit for exposed credentials.
Example
kubectl get secrets -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.type}{"\n"}{end}'kubectl delete (cascade false)Deletes the deployment controller but leaves the pods running for investigation.
Example
kubectl delete deployment nginx --cascade=orphankubectl cp (snapshot)Extracts logs or files from a compromised pod for forensic analysis.
Example
kubectl cp my-pod:/var/log/app.log ./evidence.logkubectl patch (finalizers)Removes finalizers to force deletion of stuck resources.
Example
kubectl patch pvc my-pvc -p '{"metadata":{"finalizers":null}}'kubectl diff (server-side)Previews changes using server-side apply logic.
Example
kubectl diff -f manifest.yaml --server-sidekubectl replace (force)Forces resource replacement by deleting and recreating it immediately.
Example
kubectl replace --force -f pod.yamlkubectl get (watch)Watches for changes to the list of pods in real-time.
Example
kubectl get pods -wkubectl completion bashGenerates and sources the bash auto-completion code for the current shell.
Example
source <(kubectl completion bash)kubectl completion zshGenerates and sources the zsh auto-completion code.
Example
source <(kubectl completion zsh)kubectl convertConverts config files between different API versions (requires plugin).
Example
kubectl convert -f deployment.yaml --output-version apps/v1kubectl get --raw (nodes)Fetches raw metrics directly from a specific node.
Example
kubectl get --raw /api/v1/nodes/node1/proxy/metricskubectl get (jsonpath conditional)Lists only nodes that are currently cordon/unschedulable.
Example
kubectl get nodes -o jsonpath='{.items[?(@.spec.unschedulable)].metadata.name}'kubectl get (custom columns images)Audits all images running across the entire cluster.
Example
kubectl get pods -A -o custom-columns='NS:.metadata.namespace,POD:.metadata.name,IMAGE:.spec.containers[*].image'kubectl describe (sidecar)Inspects sidecar container details often used in service meshes.
Example
kubectl describe pod my-pod | grep -A 10 'istio-proxy'kubectl explain (recursive)Recursively prints all fields and sub-fields for a resource spec.
Example
kubectl explain deployment.spec --recursivekubectl drain (force)Forces a node drain even if there are pods not managed by a controller.
Example
kubectl drain node-1 --force --ignore-daemonsetskubectl auth can-i (list)Lists all allowed actions for a specific service account.
Example
kubectl auth can-i --list --as=system:serviceaccount:ns:sakubectl set serviceaccountUpdates the service account used by a workload resource.
Example
kubectl set serviceaccount deployment/web my-sakubectl run (curl)Launches a temporary curl pod to test internal cluster connectivity.
Example
kubectl run curl-test --image=curlimages/curl -it --rm -- shkubectl run (dns)Launches a temporary pod to verify internal DNS resolution.
Example
kubectl run dns-test --image=busybox -it --rm -- nslookup kubernetes.defaultkubectl delete allDeletes all resources in a namespace (use with extreme caution).
Example
kubectl delete all --all -n test-nsChecks whether a Kubernetes cluster is deployed securely by running the CIS Kubernetes Benchmark tests against nodes and control plane.
Hunts for security weaknesses in Kubernetes clusters from inside or outside, reporting exposed components and known issues. Archived upstream but still informative.
The Docker CLI: build, run and inspect containers and images, and audit their configuration, mounts, capabilities and networks.
Amazon’s official command line for AWS: manage IAM, S3, EC2, Lambda and every other service, and audit an account’s configuration.
The gcloud CLI for Google Cloud: manage projects, IAM, Compute Engine, GKE and storage from the terminal.