---
title: "kubectl"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/kubectl
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# kubectl

kubectl is the command-line tool for talking to a Kubernetes cluster. Use it to deploy apps, inspect and manage resources, stream logs, and debug running pods.

13 Categories30 Sections41 ExamplesPublished: 27 May 2026

kubectlKubernetesK8sCLIkubeconfigPodsContainer OrchestrationDevOps

[Markdown for AI(opens in a new tab)](/kubectl/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Containers & Kubernetes](/series/containers--kubernetes)7/7

[PreviousDocker Swarm](/cheatsheets/docker-swarm)

All posts in this series (7)

Cheatsheets7

1.  [Docker](/cheatsheets/docker)
2.  [Helm](/cheatsheets/helm)
3.  [Kubernetes](/cheatsheets/kubernetes)
4.  [Docker Compose](/cheatsheets/docker-compose)
5.  [Dockerfile](/cheatsheets/dockerfile)
6.  [Docker Swarm](/cheatsheets/docker-swarm)
7.  [kubectlYou are here](/cheatsheets/kubectl)

kubectl is the command-line tool you use to talk to a Kubernetes cluster. Whatever you can do through a dashboard, you can do faster here: deploy apps, inspect resources, stream logs, run commands inside containers, and take nodes in and out of service.

The mental model is simple. You tell kubectl a verb and a resource (`get pods`, `delete deployment`, `apply -f file.yaml`), it talks to the cluster’s API server, and the cluster does the work. Get comfortable with `get`, `describe`, `logs`, and `apply` and you’re already most of the way there.

## [Key features](#key-features)

-   **One tool for everything**: deploy, inspect, update, scale, and debug from a single CLI.
-   **Declarative or imperative**: apply YAML you keep in Git, or fire off quick one-off commands.
-   **Flexible output**: reshape any command into wide tables, JSON, YAML, JSONPath, or custom columns for scripting.
-   **Built-in debugging**: stream logs, exec into containers, attach ephemeral debug containers, and forward ports to your laptop.

[Getting Started](#category-getting-started)

-   [Setup and Version](#section-setup-and-version)
-   [Contexts and Namespaces](#section-contexts-and-namespaces)
-   [Discovering the API](#section-discovering-the-api)

[Creating and Applying Resources](#category-creating-resources)

-   [Apply Manifests](#section-apply-manifests)
-   [Imperative Create](#section-imperative-create)

[Viewing and Finding Resources](#category-viewing-resources)

-   [Get and Describe](#section-get-and-describe)
-   [Output Formats](#section-output-formats)
-   [Filtering and Sorting](#section-filtering-and-sorting)

[Updating Resources](#category-updating-resources)

-   [Rollouts](#section-rollouts)
-   [Scaling](#section-scaling)
-   [Labels and Patches](#section-labels-and-patches)

[Interacting With Pods](#category-interacting-with-pods)

-   [Logs](#section-logs)
-   [Exec and Debug](#section-exec-and-debug)
-   [Port-Forward and Copy](#section-port-forward-and-cp)
-   [Resource Usage](#section-resource-usage)

[Cluster and Node Management](#category-cluster-management)

-   [Cluster Info](#section-cluster-info)
-   [Node Maintenance](#section-node-maintenance)

[Handy One-Liners](#category-handy-patterns)

-   [Useful Patterns](#section-useful-patterns)

[Contexts & kubeconfig](#category-contexts-kubeconfig)

-   [Inspecting & Switching Contexts](#section-inspecting-switching-contexts)
-   [Viewing & Merging kubeconfig](#section-merged-kubeconfig)

[Namespaces & Labels](#category-namespaces-labels)

-   [Namespaces](#section-creating-namespaces)
-   [Labels, Annotations & Selectors](#section-labels-selectors)

[Rollouts & Scaling](#category-rollouts-scaling)

-   [Managing Rollouts](#section-managing-rollouts)
-   [Scaling & Autoscaling](#section-scaling-autoscaling)

[Debugging & Troubleshooting](#category-debugging-troubleshooting)

-   [Ephemeral & Node Debug Containers](#section-debug-containers)
-   [Events, Logs & Metrics](#section-events-logs-metrics)

[RBAC & Access](#category-rbac-access)

-   [Checking Permissions & Identity](#section-checking-permissions)
-   [RBAC Objects & Impersonation](#section-rbac-objects)

[Output, JSONPath & Kustomize](#category-output-jsonpath-kustomize)

-   [JSONPath, Columns & Explain](#section-output-shaping)
-   [Diff, Dry-run & Kustomize](#section-diff-dryrun-kustomize)

No commands found

Try adjusting your search term

## Getting Started

Check your setup, switch between clusters, and find your way around the API.

### Setup and Version

Confirm kubectl can reach your cluster, then make the tool faster to type.

#### Best Practices

-   Add the completion line and alias to your shell profile so they survive new terminals.
-   Keep kubectl within one minor version of your cluster. A newer or older client can behave oddly against the API.

#### Common Errors

-   **The connection to the server localhost:8080 was refused:** kubectl has no kubeconfig and is falling back to a local default. Set KUBECONFIG or copy a valid config to ~/.kube/config.

#### Keywords

versioncompletionaliaskubeconfig

#### Check the client and cluster versions

If the server version is missing, kubectl can't reach the cluster yet. Check your kubeconfig before anything else.

Code

Terminal window

```
# Show both the kubectl (client) and cluster (server) versionskubectl version
# Just the client, formatted as YAMLkubectl version --client -o yaml
```

#### Turn on autocomplete and a short alias

Autocomplete works for resource names too, not just flags, so you tab-complete pod names. It's the single biggest quality-of-life win.

Code

Terminal window

```
# Load completion for the current shell (add to ~/.bashrc to keep it)source <(kubectl completion bash)   # use 'zsh' for zsh
# Most people alias kubectl to 'k' since you type it all dayalias k=kubectl
```

### Contexts and Namespaces

A context bundles a cluster, a user, and a namespace. Switching contexts is how you move between clusters.

#### Best Practices

-   Set a default namespace per context so you don't accidentally run commands against the wrong one.
-   Treat production as its own context and double-check current-context before any write command.

#### Common Errors

-   **Resources seem to be missing even though you know they exist:** You're probably in the wrong namespace. Add -n <namespace> or -A to list across all of them.

#### Keywords

contextnamespaceconfiguse-context

#### See where you're pointed and switch clusters

Every command runs against the current context. When something looks wrong, check this first. You might be on the wrong cluster.

Code

Terminal window

```
# Which contexts exist, and which one is active?kubectl config get-contextskubectl config current-context
# Switch to another cluster/contextkubectl config use-context staging
```

#### Set a default namespace so you stop typing -n

Code

Terminal window

```
# Pin the current context to a namespacekubectl config set-context --current --namespace=payments
# Override per-command when you need tokubectl get pods -n kube-systemkubectl get pods -A            # -A means all namespaces
```

### Discovering the API

When you forget a field name or a resource's short name, ask the cluster instead of guessing.

#### Keywords

explainapi-resourcesshort names

#### Look up resource types and their fields

api-resources is how you learn that 'deployments' is 'deploy' for short and 'services' is 'svc'. explain saves a trip to the docs.

Code

Terminal window

```
# List every resource type, its short name, and API groupkubectl api-resources
# Read the schema for a field, drilling down with dotskubectl explain pod.spec.containers
```

## Creating and Applying Resources

Two styles ship work to the cluster. Declarative means applying a file, imperative means running a command. Lean on declarative.

### Apply Manifests

Declarative management. You describe the desired state in YAML and let Kubernetes reconcile.

#### Best Practices

-   Keep manifests in Git and apply them through a pipeline. The cluster should mirror your repo, not the other way around.
-   Run kubectl diff before applying to production so changes are never a surprise.

#### Common Errors

-   **The "metadata.annotations: Too long" error after switching from create to apply:** A resource first made with 'create' lacks apply's tracking annotation. Re-create it with apply, or use --server-side apply going forward.

#### Keywords

applymanifestdiffdry-run

#### Apply a file, a folder, or a URL

apply creates resources that don't exist and updates the ones that do, so the same command works for the first deploy and every change after.

Code

Terminal window

```
# A single manifestkubectl apply -f deployment.yaml
# Every manifest in a directory (great for a whole app)kubectl apply -f ./k8s/
# Straight from a URLkubectl apply -f https://example.com/app.yaml
```

#### Preview changes before you apply them

diff is your safety net. Run it in CI and in code review so nobody is surprised by what apply actually does.

Code

Terminal window

```
# Show exactly what would change against the live clusterkubectl diff -f deployment.yaml
# Validate without touching anything (server-side)kubectl apply -f deployment.yaml --dry-run=server
```

### Imperative Create

Quick, one-off commands for prototyping or generating starter YAML.

#### Advanced Notes

-   **Imperative is fine for learning, declarative for real work:** Imperative commands are great in a terminal or an exam, but they leave no record of intent. For anything that outlives the afternoon, generate YAML and commit it.

#### Keywords

createrungenerate yaml

#### Spin up common resources from the command line

Code

Terminal window

```
# A deployment from an imagekubectl create deployment web --image=nginx:1.27
# A one-shot job and a scheduled cronjobkubectl create job backup --image=postgres -- pg_dump mydbkubectl create cronjob nightly --image=busybox \  --schedule="0 2 * * *" -- /bin/sh -c 'echo run'
```

#### Let kubectl write the YAML for you

This is the fastest way to get a correct starting manifest. Generate it, tweak it, and from then on manage it with apply.

Code

Terminal window

```
# Generate a manifest without creating anything, then edit and commit itkubectl create deployment web --image=nginx \  --dry-run=client -o yaml > deployment.yaml
```

## Viewing and Finding Resources

get for the quick list, describe for the full story, and output formats for scripting.

### Get and Describe

The two commands you'll run more than any other.

#### Common Errors

-   **A pod is stuck in Pending and you don't know why:** Run kubectl describe pod <name> and read the Events. It usually says it can't schedule (no node fits) or can't pull the image.

#### Keywords

getdescribewidewatch

#### List resources, then dig into one

describe is where you find out WHY a pod is stuck. Scroll to the Events section at the bottom first.

Code

Terminal window

```
# A quick list, then the same list with node and IP columnskubectl get podskubectl get pods -o wide
# The full picture: events, conditions, and recent state changeskubectl describe pod web-7d9f
```

#### Watch resources change in real time

Code

Terminal window

```
# Refresh the list as things change (Ctrl-C to stop)kubectl get pods -w
# Combine resource types in one callkubectl get deploy,svc,pods
```

### Output Formats

Reshape output for humans or for scripts with -o.

#### Advanced Notes

-   **Find the JSONPath you need:** Run the command with -o yaml first to see the structure, then walk the same path with -o jsonpath. The field names match one to one.

#### Keywords

jsonyamljsonpathcustom-columns

#### Pull out exactly the fields you need

JSONPath and custom-columns let you script against kubectl without piping through jq. Handy in CI checks and quick reports.

Code

Terminal window

```
# The whole object as YAML (handy for copying spec fields)kubectl get pod web -o yaml
# Just the names, one per line, via JSONPathkubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Your own table with custom columnskubectl get pods \  -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName'
```

### Filtering and Sorting

Narrow a long list down to the resources you actually care about.

#### Best Practices

-   Label everything consistently (app, tier, env). Good labels make every selector, service, and dashboard easier.

#### Keywords

selectorlabelfield-selectorsort-by

#### Filter by label, field, and sort the results

Label selectors are the same ones your Services and Deployments use, so filtering with -l mirrors how Kubernetes wires things together.

Code

Terminal window

```
# Only pods with a matching labelkubectl get pods -l app=web,tier=frontend
# Only pods that are actually runningkubectl get pods --field-selector=status.phase=Running
# Sort by how many times each pod has restartedkubectl get pods \  --sort-by='.status.containerStatuses[0].restartCount'
```

## Updating Resources

Roll out new versions, scale up and down, and tweak live objects.

### Rollouts

Ship a new image and control or undo the rollout if it goes wrong.

#### Common Errors

-   **rollout status hangs and never completes:** New pods are probably crash-looping or failing health checks. Check kubectl get pods and kubectl logs, then roll back with rollout undo.

#### Keywords

rolloutset imageundohistory

#### Update an image and watch the rollout

A Deployment rolls out gradually, replacing old pods with new ones, so users keep getting served while the update happens.

Code

Terminal window

```
# Change the container image, which triggers a rolling updatekubectl set image deployment/web web=nginx:1.27.1
# Follow the rollout until it finishes (or fails)kubectl rollout status deployment/web
```

#### Roll back a bad release

undo is your fast path out of a broken deploy. It's much quicker than editing the image back by hand under pressure.

Code

Terminal window

```
# See past revisionskubectl rollout history deployment/web
# Go back to the previous versionkubectl rollout undo deployment/web
# Or jump to a specific revisionkubectl rollout undo deployment/web --to-revision=3
```

### Scaling

Add or remove replicas, by hand or automatically.

#### Keywords

scaleautoscalereplicashpa

#### Scale manually or set up autoscaling

autoscale creates a HorizontalPodAutoscaler. It needs the metrics-server running in the cluster to read CPU usage.

Code

Terminal window

```
# Run four copies of the appkubectl scale deployment/web --replicas=4
# Or let Kubernetes scale on CPU between 2 and 10 replicaskubectl autoscale deployment/web --min=2 --max=10 --cpu-percent=70
```

### Labels and Patches

Make small, targeted changes to a live resource without re-applying the whole file.

#### Advanced Notes

-   **Live edits drift from your manifests:** Anything you change with edit, patch, or label only lives in the cluster. If you manage the resource with apply, fold the change back into your YAML or the next apply will revert it.

#### Keywords

labelannotatepatchedit

#### Add labels and patch a single field

Use patch for scripted, surgical edits. Use 'kubectl edit' when you'd rather open the live object in your editor and change it by hand.

Code

Terminal window

```
# Tag a pod with a label (use --overwrite to change an existing one)kubectl label pod web-7d9f environment=prod
# Change one field with a strategic merge patchkubectl patch deployment/web \  -p '{"spec":{"replicas":5}}'
```

## Interacting With Pods

Read logs, run commands inside containers, reach a pod from your laptop, and debug.

### Logs

The first place to look when an app misbehaves.

#### Common Errors

-   **a container name must be specified for pod ...:** The pod has more than one container. Add -c <container>, or use --all-containers to stream all of them.

#### Keywords

logsfollowpreviouscontainer

#### Read and stream logs

\--previous is the one people forget. After a crash loop, it shows the logs from the container that just died, which is exactly what you need.

Code

Terminal window

```
# Stream logs live (-f), only the last 100 lines to startkubectl logs -f web-7d9f --tail=100
# Pick a container in a multi-container podkubectl logs web-7d9f -c sidecar
# Logs from the previous container after a crash/restartkubectl logs web-7d9f --previous
```

### Exec and Debug

Get a shell or a one-off command inside a container, or attach a debug container.

#### Best Practices

-   Prefer kubectl debug over baking debugging tools into production images. The image stays small and the tools show up only when you need them.

#### Keywords

execdebugrunephemeral

#### Run a command or open a shell inside a pod

Everything after -- runs inside the container. Use /bin/sh if /bin/bash isn't there, since slim images often ship without bash.

Code

Terminal window

```
# One-off commandkubectl exec web-7d9f -- env
# Interactive shell (-it = interactive + TTY)kubectl exec -it web-7d9f -- /bin/sh
```

#### Debug a pod that has no shell at all

kubectl debug adds an ephemeral container that shares the target's namespaces, so you can inspect a distroless image that has no shell of its own.

Code

Terminal window

```
# Attach a temporary debug container with full toolskubectl debug -it web-7d9f \  --image=busybox --target=web
# Or launch a throwaway pod to poke the networkkubectl run tmp --rm -it --image=busybox -- sh
```

### Port-Forward and Copy

Reach a pod directly from your machine and move files in or out.

#### Keywords

port-forwardcptunnel

#### Tunnel a local port and copy files

port-forward reaches an internal service or a database without exposing it to the world.

Code

Terminal window

```
# Open localhost:8080 straight to the pod's port 80kubectl port-forward pod/web-7d9f 8080:80
# Forward to whatever pod a Service points atkubectl port-forward svc/web 8080:80
# Copy a file out of a pod (tar must exist in the container)kubectl cp default/web-7d9f:/var/log/app.log ./app.log
```

### Resource Usage

See which pods and nodes are actually using CPU and memory.

#### Keywords

topmetricscpumemory

#### Check live CPU and memory

top needs the metrics-server add-on. If it errors out, that component probably isn't installed in the cluster.

Code

Terminal window

```
# Usage per node and per podkubectl top nodeskubectl top pods --all-namespaces
```

## Cluster and Node Management

Inspect the cluster as a whole and safely take nodes out of service for maintenance.

### Cluster Info

A quick health read on the control plane and nodes.

#### Keywords

cluster-infoget nodesevents

#### Look at the cluster and recent events

Check the cluster-wide events list early during an incident. It often points straight at the failing component.

Code

Terminal window

```
# Control plane endpointskubectl cluster-info
# Node list with readiness and versionskubectl get nodes -o wide
# Recent events across the cluster, newest lastkubectl get events --sort-by=.metadata.creationTimestamp
```

### Node Maintenance

Drain a node before you patch or reboot it, then bring it back.

#### Common Errors

-   **drain refuses to proceed and complains about DaemonSets or local data:** Add --ignore-daemonsets (DaemonSet pods are recreated anyway) and --delete-emptydir-data if you accept losing scratch data on that node.

#### Advanced Notes

-   **Taints vs cordon:** cordon just stops new scheduling. A taint is more expressive. It repels pods unless they carry a matching toleration, which is how you reserve nodes for specific workloads like GPUs.

#### Keywords

cordondraintaintuncordon

#### Safely take a node down and bring it back

drain moves pods off the node gracefully so workloads keep running elsewhere. Always cordon or drain before a reboot.

Code

Terminal window

```
# Stop scheduling new pods herekubectl cordon node-1
# Evict the existing pods (skip DaemonSet-managed ones)kubectl drain node-1 --ignore-daemonsets --delete-emptydir-data
# ...do your maintenance, then allow scheduling againkubectl uncordon node-1
```

## Handy One-Liners

A few commands worth keeping in your back pocket.

### Useful Patterns

Small recipes that come up again and again.

#### Best Practices

-   Save your favorite one-liners as shell functions or aliases. The ones you reach for during an incident should be muscle memory.

#### Common Errors

-   **A namespace is stuck in Terminating forever:** A finalizer is usually blocking it. Find the offending resource and clear its finalizer, rather than force-deleting the namespace, which can orphan resources.

#### Keywords

secretdecodeforce deletejsonpath

[Learn more](https://kubernetes.io/docs/reference/kubectl/cheatsheet/)

#### Decode a Secret without leaving the terminal

Secret values are only base64-encoded, not encrypted at rest by default, so anyone with get access can read them. Lock down RBAC accordingly.

Code

Terminal window

```
# Secrets are base64-encoded; decode one valuekubectl get secret db-creds \  -o jsonpath='{.data.password}' | base64 -d
```

#### Force-delete a pod stuck in Terminating

Use this sparingly. It tells the API to forget the pod immediately even if the node never confirmed it stopped, which can leave orphaned processes if the node is actually alive.

Code

Terminal window

```
# Last resort when a pod won't go awaykubectl delete pod web-7d9f --grace-period=0 --force
```

## Contexts & kubeconfig

Switch between clusters, users, and namespaces, and manage merged kubeconfig files.

### Inspecting & Switching Contexts

List contexts, see which is active, and change the default context or namespace.

#### Best Practices

-   Set a default namespace per context with set-context --current --namespace=... instead of typing -n every time; it kills a whole class of wrong-namespace mistakes.

#### Common Errors

-   **error: current-context must exist in order to minify.:** No context is selected. Run kubectl config use-context <name> first, or check kubectl config get-contexts.

#### Keywords

configcontextnamespace

#### List and switch contexts

get-contexts shows every cluster/user/namespace triple; use-context sets the active one.

Code

Terminal window

```
kubectl config get-contexts       # list contexts (* marks current)kubectl config current-context    # print the active context namekubectl config use-context my-cluster # make my-cluster the default
```

#### Pin a default namespace onto the current context

Sets a default namespace so you can drop -n on every command against this context.

Code

Terminal window

```
kubectl config set-context --current --namespace=team-a
```

### Viewing & Merging kubeconfig

Inspect the merged config and combine several kubeconfig files for one invocation.

#### Best Practices

-   Keep per-cluster kubeconfig files separate and merge them via KUBECONFIG rather than pasting everything into one file you might clobber.

#### Keywords

kubeconfigviewKUBECONFIG

#### View the config for the current context only

\--minify narrows output to the active context; --raw exposes full credentials, so handle it carefully.

Code

Terminal window

```
kubectl config view --minify   # only the current context (redacted)kubectl config view --raw      # merged config incl. cert/key data
```

#### Merge multiple kubeconfig files

Colon-separated list merges files for one command (use ; on Windows).

Code

Terminal window

```
KUBECONFIG=~/.kube/config:~/.kube/config-prod kubectl config view
```

## Namespaces & Labels

Create namespaces and organize or filter resources with labels, annotations, and selectors.

### Namespaces

Create namespaces imperatively or generate their manifests.

#### Best Practices

-   Generate manifests with --dry-run=client -o yaml and commit them, rather than creating resources imperatively and losing the definition.

#### Keywords

namespacecreatedry-run

#### Create a namespace or generate its manifest

\--dry-run=client -o yaml renders the manifest without touching the cluster. Handy for GitOps.

Code

Terminal window

```
kubectl create namespace team-akubectl create namespace team-a --dry-run=client -o yaml > ns.yaml
```

### Labels, Annotations & Selectors

Attach metadata and filter resources with equality, set-based, and field selectors.

#### Best Practices

-   Use --field-selector for built-in fields (cheap, server-side) and -l for your own metadata; do not grep full output when a selector filters at the API.

#### Common Errors

-   **label ... already has a value (v1), and --overwrite is false.:** Re-labeling needs permission to change an existing value. Add --overwrite.

#### Keywords

labelselectorfield-selector

#### Label and annotate resources

Labels are selectable identifying metadata; annotations are non-selectable free-form metadata.

Code

Terminal window

```
kubectl label pods my-pod version=v1kubectl label pods my-pod version=v2 --overwrite # required to changekubectl annotate pods my-pod description='owned by team-a'
```

#### Filter with label and field selectors

\-l selects on your labels; --field-selector filters built-in fields like status.phase server-side.

Code

Terminal window

```
kubectl get pods -l 'environment in (prod,qa)' # set-based selectorkubectl get pods --show-labels                 # add a LABELS columnkubectl get pods --field-selector=status.phase=Running # filter on fields
```

## Rollouts & Scaling

Drive, inspect, roll back, and scale Deployments and other rollout-capable workloads.

### Managing Rollouts

Monitor progress, review history, and roll back or restart Deployments.

#### Best Practices

-   Use kubectl rollout status in CI/CD as a gate. It exits non-zero on a failed or timed-out rollout, so the pipeline catches a bad deploy automatically.

#### Keywords

rolloutundorestart

#### Watch, roll back, and restart

rollout restart re-creates pods without changing the spec; undo reverts to a prior revision.

Code

Terminal window

```
kubectl rollout status deployment/my-app   # block until complete/failedkubectl rollout history deployment/my-app  # list revisionskubectl rollout undo deployment/my-app --to-revision=2 # roll backkubectl rollout restart deployment/my-app  # re-create pods (e.g. rotate secret)
```

-   rollout pause and rollout resume let you batch several edits into a single rollout.

### Scaling & Autoscaling

Set fixed replica counts or attach a HorizontalPodAutoscaler.

#### Best Practices

-   HPAs need metrics-server and per-container resources.requests.cpu; without both, the HPA shows TARGETS <unknown>/80% and never scales.

#### Common Errors

-   **HPA shows TARGETS <unknown>/80%.:** Install metrics-server (verify with kubectl top pods) and set resources.requests.cpu on the Deployment's containers.

#### Keywords

scaleautoscalehpa

#### Scale manually or add an HPA

\--current-replicas makes the scale conditional; autoscale creates an HPA targeting 80% CPU.

Code

Terminal window

```
kubectl scale deployment/my-app --replicas=5kubectl scale deployment/my-app --replicas=3 --current-replicas=2 # guardedkubectl autoscale deployment/my-app --min=2 --max=10 --cpu-percent=80
```

## Debugging & Troubleshooting

Inspect failing pods and nodes with ephemeral containers, events, describe, logs, and live metrics.

### Ephemeral & Node Debug Containers

Attach debug containers to running pods or nodes, even for distroless images with no shell.

#### Best Practices

-   Use --copy-to to debug a copy of a pod when you must not disturb the live one.

#### Keywords

debugephemeralnode

#### Debug a pod or a node

kubectl debug (stable since 1.25) injects an ephemeral container or a privileged node pod without editing the workload.

Code

Terminal window

```
# share the target's process namespace (great for distroless)kubectl debug -it my-pod --image=busybox:1.28 --target=my-container# a node debug pod with the host mounted at /hostkubectl debug node/my-node -it --image=ubuntu
```

### Events, Logs & Metrics

Read events, previous-container logs, and live resource usage to diagnose failures.

#### Best Practices

-   Reach for kubectl logs <pod> --previous first on CrashLoopBackOff. The current container is already restarted, so only the previous instance's logs explain the crash.

#### Common Errors

-   **error: Metrics API not available on kubectl top.:** metrics-server is missing or not ready. Install and verify it (kubectl get deployment metrics-server -n kube-system); top and HPAs both depend on it.

#### Keywords

eventslogstop

#### Events, crash logs, and usage

For a CrashLoopBackOff, logs --previous shows why the dead container exited; the live one is already gone.

Code

Terminal window

```
kubectl events --for pod/my-pod # dedicated events cmd (GA 1.28)kubectl get events --sort-by=.metadata.creationTimestamp # portable formkubectl logs my-pod --previous  # logs from the crashed instancekubectl top pods --containers    # live CPU/memory (needs metrics-server)
```

## RBAC & Access

Check permissions, inspect your identity, and create RBAC objects and service accounts.

### Checking Permissions & Identity

Verify what you can do and who the API server thinks you are.

#### Best Practices

-   Before granting a Role, dry-run access with kubectl auth can-i ... --as=<subject>. That is cheaper and safer than binding, testing, then revoking.

#### Common Errors

-   **kubectl auth whoami returns "the server could not find the requested resource".:** The SelfSubjectReview API is only on clusters 1.27+ (GA 1.28). Upgrade the cluster, or use kubectl config view --minify to see the configured user.

#### Keywords

authcan-iwhoami

#### can-i and whoami

can-i answers permission questions without side effects; auth whoami is GA since Kubernetes 1.28.

Code

Terminal window

```
kubectl auth can-i create deployments            # prints yes/nokubectl auth can-i delete pods --namespace=team-a # scope to a namespacekubectl auth can-i --list                        # every allowed actionkubectl auth whoami                              # your user + groups (GA 1.28)
```

### RBAC Objects & Impersonation

Create service accounts, roles, and bindings, and test access by impersonating a subject.

#### Best Practices

-   Use --clusterrole with clusterrolebinding for cluster-wide access; keep Roles namespaced and least-privilege by default.

#### Keywords

rolerolebindingimpersonation

#### Create RBAC objects and impersonate

\--as impersonates a user or service account (needs impersonate privilege) to check effective access.

Code

Terminal window

```
kubectl create serviceaccount ci-deployerkubectl create role pod-reader --verb=get,list,watch --resource=podskubectl create rolebinding read-pods --role=pod-reader \  --serviceaccount=default:ci-deployerkubectl get pods --as=system:serviceaccount:default:ci-deployer # verify
```

## Output, JSONPath & Kustomize

Shape output precisely, preview changes safely, and apply Kustomize overlays.

### JSONPath, Columns & Explain

Extract exact fields, build custom tables, and read field documentation.

#### Best Practices

-   Prefer server-side jsonpath/custom-columns over piping full output through awk/grep. It is exact and version-stable.

#### Keywords

jsonpathcustom-columnsexplain

#### Shape output and read schema

jsonpath and custom-columns pull exact fields; explain documents any resource path.

Code

Terminal window

```
kubectl get pods -o jsonpath='{.items[*].metadata.name}'kubectl get nodes -o custom-columns='NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'kubectl explain deployment.spec.strategy --recursive
```

-   go-template works too, e.g. decode a secret with -o go-template='{{index .data "tls.crt" | base64decode}}'.

### Diff, Dry-run & Kustomize

Preview what apply would change and build Kustomize overlays with the built-in kustomize.

#### Best Practices

-   Run kubectl diff -f before every production apply. It turns a blind apply into a reviewed change and shows unexpected drift.

#### Common Errors

-   **unknown flag: --dry-run printing true/false behavior.:** The bare boolean --dry-run was removed. Use --dry-run=client (local) or --dry-run=server (API-validated).

#### Keywords

diffdry-runkustomize

#### Preview changes and apply an overlay

\--dry-run takes client or server (the bare boolean form was removed); -k uses the built-in Kustomize, no separate binary.

Code

Terminal window

```
kubectl diff -f app.yaml                    # what apply would changekubectl apply -f app.yaml --dry-run=server  # validate against the APIkubectl apply -k ./overlays/prod            # build + apply a kustomizationkubectl kustomize ./overlays/prod           # render without applying
```

Was this useful?

## Tags

#Kubectl#Kubernetes#K8s#CLI#Kubeconfig#Pods#Container Orchestration#DevOps

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=kubectl&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl&title=kubectl&summary=kubectl%20is%20the%20command-line%20tool%20for%20talking%20to%20a%20Kubernetes%20cluster.%20Use%20it%20to%20deploy%20apps%2C%20inspect%20and%20manage%20resources%2C%20stream%20logs%2C%20and%20debug%20running%20pods.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=kubectl%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl&text=kubectl "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl&title=kubectl "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl&t=kubectl "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl&media=&description=kubectl%20is%20the%20command-line%20tool%20for%20talking%20to%20a%20Kubernetes%20cluster.%20Use%20it%20to%20deploy%20apps%2C%20inspect%20and%20manage%20resources%2C%20stream%20logs%2C%20and%20debug%20running%20pods. "Share on Pinterest")[Email](<mailto:?subject=kubectl&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fkubectl>)

## Comments

## You might also enjoy

More posts on similar topics

## [Kubernetes](/cheatsheets/kubernetes)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   Container Orchestration
-   Cloud Native
-   Cluster Management

Kubernetes is the de facto standard for container orchestration. It automates deployment, scaling, and management of containerized applications across clusters of machines. Configuration is declarativ

#Kubernetes#Kubectl#Containers+5 tags

[read more](/cheatsheets/kubernetes)

## [Helm](/cheatsheets/helm)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   Helm
-   Package Management
-   Cloud Native

Helm is the package manager for Kubernetes that simplifies the deployment, management, and upgrade of applications. It uses charts, which are templated Kubernetes manifests, to build reusable, configu

#Helm#Kubernetes#Package Manager+5 tags

[read more](/cheatsheets/helm)

## [Docker Swarm](/cheatsheets/docker-swarm)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Docker
-   Containers
-   Orchestration
-   Deployment

This cheatsheet is a reference for managing Docker Swarm clusters, services, and stacks. It covers the commands and best practices for scaling, updating, and monitoring your swarm applications.

#Docker Swarm#Orchestration#Containers+4 tags

[read more](/cheatsheets/docker-swarm)

## [Docker](/cheatsheets/docker)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Docker
-   Containers
-   Deployment

Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run applicati

#Docker#Containers#Images+3 tags

[read more](/cheatsheets/docker)

## [Docker Compose](/cheatsheets/docker-compose)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure application services, networks, and volumes. This cheatsheet provides a quick re

[read more](/cheatsheets/docker-compose)

## [Dockerfile](/cheatsheets/dockerfile)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

This cheat sheet covers the core Dockerfile instructions, best practices, and common pitfalls for building small, secure Docker images. Each section pairs a Dockerfile snippet with the build output it

[read more](/cheatsheets/dockerfile)

6 related posts
