Vibe monitoring with Last9 MCP: Ask your agent to fix production issues! Setup →
Last9 Last9

The Only Kubectl Commands Cheat Sheet You’ll Ever Need

Here’s your go-to kubectl commands cheat sheet! Jump into Kubernetes management with these handy commands and make your life easier.

Oct 30th, ‘24
Kubectl Commands Cheat Sheet
See How Last9 Works

Unified observability for all your telemetry. Open standards. Simple pricing.

Talk to us

Whether you're investigating a failed deployment, checking logs for a misbehaving pod, or scaling a service during peak traffic, kubectl is often the first tool you reach for.

This cheat sheet is a curated set of the ones that come up often in production scenarios: debugging, inspecting workloads, applying changes, and validating configuration.

Each section is organized around common operational tasks, not Kubernetes object types, so you spend less time searching and more time solving the issue at hand.

TL;DR; Common kubectl Commands by Task

Inspect What’s Running

Command Description
kubectl get pods List pods in the current namespace.
kubectl get pods -o wide Show pod IPs, assigned nodes, and restart counts.
kubectl get pods --all-namespaces Useful when you're unsure which namespace a pod is in.
kubectl get deployments View active deployments in the namespace.
kubectl get svc Check which services are currently exposed.
kubectl get nodes List all cluster nodes.
kubectl describe node <node> Get node-level details like resource pressure and taints.

Investigate a Pod

Command Description
kubectl describe pod <pod> View container state, event logs, and restart reasons.
kubectl logs <pod> Stream logs from a running container.
kubectl logs -p <pod> Access logs from a previous container instance.
kubectl exec -it <pod> -- /bin/sh Start a shell session inside the pod. Use /bin/bash if available.

Apply Changes, Scale, and Roll Back

Command Description
kubectl apply -f <file>.yaml Create or update resources using a config file.
kubectl scale deployment <name> --replicas=3 Manually adjust the number of replicas.
kubectl rollout status deployment/<name> Track the status of a deployment rollout.
kubectl rollout undo deployment/<name> Revert to the previous deployment version.
kubectl edit deployment <name> Inline-edit the deployment in your default editor.

Debug Configs and Resource Usage

Command Description
kubectl get configmaps List ConfigMaps in the current namespace.
kubectl get secrets Confirm whether Secrets are present and accessible.
kubectl get events --sort-by=.metadata.creationTimestamp View recent events, sorted by time.
kubectl top pods See live CPU and memory usage per pod.
kubectl top nodes View overall resource usage across nodes.

Local Testing and Context Switching

Command Description
kubectl port-forward <pod> 8080:80 Forward local port 8080 to a pod’s port 80 for local access.
kubectl config use-context <context> Switch kubeconfig contexts (e.g., between clusters or environments).
💡
If you're still unclear about how pods relate to nodes, this guide breaks down the difference with practical examples.

Frequently Used kubectl Commands

These commands cover 80% of your daily Kubernetes workflow—checking the status of resources, inspecting issues, deleting broken workloads, and filtering by conditions. They’re the starting point for most day-to-day tasks.

List Resources Across the Cluster

Quick visibility into what’s running and where.

# View all pods across all namespaces
kubectl get pods --all-namespaces

# List services in the current namespace
kubectl get svc

# View all nodes in the cluster
kubectl get nodes

Use kubectl get with different resource types to explore what’s deployed. Add flags like -o wide or --all-namespaces when you need broader context.

Describe Resources for More Context

Use describe when get doesn’t give you enough. It includes recent events, container status, mounted volumes, restart reasons, and more.

# Describe a specific pod in a specific namespace
kubectl describe pod <pod_name> -n <namespace_name>

This is especially useful for debugging startup failures, pending pods, or unknown crash reasons.

Delete Resources Cleanly

Be precise when deleting resources, especially in production. Always include resource type, name, and namespace.

# Delete a specific pod in a given namespace
kubectl delete pod <pod_name> -n <namespace_name>

Useful for clearing out stuck pods or triggering a redeploy when combined with automation.

Filter Resources with Field Selectors

Instead of scanning dozens of lines, use selectors to narrow down results by pod status or metadata.

# Get all running pods only
kubectl get pods --field-selector=status.phase=Running

This comes in handy when debugging stuck pods or checking which workloads are still initializing.

Debug Pods with Logs, Exec, and Resource Checks

Pods are where your application runs. When something goes wrong, errors, restarts, or high resource usage, these are the commands that help you figure out what’s happening and why.

Get Pod Logs to Identify Errors and Crashes

Logs help surface application-level issues like failed startups, stack traces, or unhandled exceptions.

# Get logs for a specific pod in a namespace
kubectl logs <pod_name> -n <namespace_name>

For multi-container pods, add the container name:

-c <container_name>

To see logs from a previous instance (useful when a pod is crashing and restarting):

kubectl logs -p <pod_name> -n <namespace_name>

Run Commands Inside Pods to Troubleshoot Issues

When logs aren’t enough, exec into the container to check environment variables, network access, or file paths.

# Open an interactive shell
kubectl exec -it <pod_name> -- /bin/bash

If bash isn’t available, fall back to /bin/sh.

For quick one-off checks:

kubectl exec <pod_name> -- env

Check Pod Resource Usage with kubectl top

If you suspect a memory leak, CPU spikes, or throttling, use kubectl top to view real-time usage.

# View CPU and memory usage for a specific pod
kubectl top pod <pod_name> -n <namespace_name>
💡
If the command doesn’t return data, the Metrics Server may be missing. Here's how to set it up.

Manage Deployments and Rollouts in Kubernetes

Deployments handle the rollout lifecycle for your workloads, creating new pods, scaling based on demand, and rolling out updates safely. These commands help you define and control that process with precision.

Create a Deployment from a Container Image

Start by creating a deployment that runs your containerized application.

# Create a deployment with a specified image
kubectl create deployment <deployment_name> --image=<container_image>

This sets up a Deployment and ReplicaSet with a single pod. For more control, define it using a YAML manifest instead.

Update a Deployment with a New Image

When pushing a new version of your app, you can update the image and track the rollout in real time.

# Update the image for a specific container
kubectl set image deployment/<deployment_name> <container_name>=<new_image>

# Monitor the rollout status
kubectl rollout status deployment/<deployment_name>

If the rollout stalls or fails, inspect the events using kubectl describe deployment <name>.

Scale a Deployment to Match Demand

Adjust the number of pod replicas to meet traffic or processing needs.

# Scale the deployment to the desired replica count
kubectl scale deployment <deployment_name> --replicas=<desired_number>

Scaling up adds pods, while scaling down safely terminates extras without downtime.

Manage Namespaces for Environment Isolation and Access Control

Namespaces in Kubernetes isolate workloads, separate environments (like staging and production), and define RBAC boundaries. They're essential in multi-tenant clusters or when multiple teams share the same infrastructure.

Create a Namespace for Logical Separation

Use namespaces to group related resources—whether by environment, team, or application boundary.

# Create a new namespace
kubectl create namespace <namespace_name>

This is often one of the first steps when provisioning a new environment.

List All Namespaces in the Cluster

Get a snapshot of all active namespaces to verify what's available or currently in use.

# List all namespaces
kubectl get namespaces

Add -o wide for additional details like status and age.

Set a Default Namespace for Your Context

Switching context avoids having to type -n <namespace> repeatedly. It’s useful when you’re focusing on one environment for an extended session.

# Set the default namespace for the current context
kubectl config set-context --current --namespace=<namespace_name>

This only affects your local kubeconfig, not the cluster-wide configuration.

Run into kubectl issues? Fix and test them faster — right from your IDE, with AI and Last9 MCP.

Last 9 Mobile Illustration

Configure Resources and Manage Metadata in Kubernetes

These commands help you inspect config details, make live changes, and attach metadata to workloads. Useful during troubleshooting, debugging, or fine-tuning deployments, without rewriting entire manifests.

View Current Cluster Context and Kubeconfig Settings

Check which cluster, namespace, and user your kubectl commands are targeting.

# View the active kubeconfig settings
kubectl config view

This helps when you're switching between environments or managing multiple clusters.

Edit Resource Definitions Without Reapplying YAML

Use kubectl edit to patch live resources directly in your default text editor. This is faster than exporting YAML, modifying it, and reapplying.

# Edit a pod in a specific namespace
kubectl edit pod <pod_name> -n <namespace_name>

Changes are applied immediately. Useful for quick tweaks, like fixing a typo in an env var or updating a probe.

Add Labels and Annotations to Group or Describe Resources

Labels help with filtering and selectors. Annotations are key-value metadata for tools and automation, not used for selection, but useful for audits or debugging.

# Add a label to a pod
kubectl label pod <pod_name> env=production

# Add an annotation to a pod
kubectl annotate pod <pod_name> description="Backend pod for service A"

To change an existing label or annotation, use the --overwrite flag.

💡
For a deeper look at how logging works beyond kubectl logs, this guide explains Kubernetes logs and where to find them.

Manage Cluster State and Node Scheduling

These commands help you check cluster-level details, inspect persistent storage, and manage node availability during maintenance or upgrades.

Show Cluster Endpoint and Configuration Details

Use this to verify API server access and check which cluster you're interacting with.

# Display cluster information and API server URLs
kubectl cluster-info

This is useful when switching between environments or troubleshooting connectivity issues.

List Persistent Volumes Across the Cluster

See which volumes are available or bound to pods—especially important for stateful workloads.

# List all persistent volumes
kubectl get persistentvolumes

To view claim status or storage class info, use:

kubectl get pv -o wide

Control Node Scheduling During Maintenance

Prevent new pods from being scheduled on a node using cordon. This is commonly used during planned maintenance or node draining.

# Mark a node as unschedulable
kubectl cordon <node_name>

# Re-enable scheduling on the node
kubectl uncordon <node_name>

This doesn’t affect existing pods; it only prevents new workloads from landing on the node.

Monitor Resource Usage and Access Internal Services

These commands help you observe live metrics, expose internal services for local testing, and inspect Kubernetes objects in structured formats. They’re handy when debugging live workloads or working with raw cluster data.

Forward Pod Ports to Your Local Machine

Access a pod’s service—like a web app or gRPC server—directly on your laptop, without exposing it via a service or ingress.

# Forward a pod port to your local machine
kubectl port-forward <pod_name> <local_port>:<remote_port> -n <namespace_name>

This is ideal for debugging locally against an in-cluster service or testing a pod without making it public.

View Live CPU and Memory Usage with kubectl top

Check which pods or nodes are under load using resource metrics. Useful during performance debugging or when tuning resource limits.

# View resource usage for nodes
kubectl top node

# View usage for pods in a namespace
kubectl top pod -n <namespace_name>

Output Resources in YAML or JSON

Inspect or export the raw configuration of resources. This is useful for debugging, editing, or version-controlling your cluster state.

# Get all pods in YAML format
kubectl get pods -o yaml

# Get a deployment in JSON format
kubectl get deployment <name> -o json

You can redirect this output to a file and use it later with kubectl apply.

💡
If you're troubleshooting memory issues in your cluster, this guide walks through how to track and understand pod memory usage.

Interact with the Kubernetes API Server Directly

These commands give you raw access to Kubernetes API resources and output formats, useful when building tooling, scripting automation, or querying data precisely.

List All Available Resource Types

Get a complete list of API resource types supported by your current cluster. This includes built-in types and any custom resources registered by CRDs.

# List all Kubernetes API resources
kubectl api-resources

Use this when working with unfamiliar clusters or building tools that rely on dynamic discovery.

Extract Fields from Output Using JSONPath

Use -o jsonpath to pull specific fields from API responses. Useful in scripts or when you only need targeted data.

# List all pod names in the current namespace
kubectl get pods -o jsonpath='{.items[*].metadata.name}'

This avoids parsing entire JSON/YAML blobs manually. You can also combine with --all-namespaces or add filters as needed.

Conclusion

This cheat sheet covers the commands you’ll reach for when something breaks, whether it's a stuck pod, a rollout gone wrong, or a service that just won’t respond.

Once you're past the basics, it’s less about what command to run and more about why things are breaking in the first place. Latency spikes, cost blowups, memory thrashing. Last9 helps you tie together metrics, logs, and traces without stitching everything manually.

Also worth exploring: write your manifests, set up kubectl aliases, or try tools like k9s, stern, and kubectx that build on top of this workflow.

🤝
If you’d like to continue the conversation, join our community on Discord! We have a dedicated channel where you can chat with other developers about your specific use case.

FAQs

What is in kubectl commands?
kubectl commands encompass various operations you can perform on Kubernetes resources, including managing pods, services, deployments, namespaces, and more. Some common commands include kubectl get, kubectl create, kubectl delete, and kubectl describe.

How to practice Kubernetes commands?
You can practice Kubernetes commands by setting up a local cluster using tools like Minikube or Kind (Kubernetes in Docker). These environments allow you to experiment with kubectl commands without affecting a live production environment.

What is the command to get all running pods?
To list all running pods across all namespaces, you can use:

kubectl get pods --all-namespaces --field-selector=status.phase=Running

Which command is used to list all the Kubernetes objects?
To list all Kubernetes objects within a specific namespace, use:

kubectl get all -n <namespace-name>

To list all objects in all namespaces, add the --all-namespaces flag:

kubectl get all --all-namespaces

Can I Use Docker Without Kubernetes?
Yes, you can use Docker independently of Kubernetes. Docker is a platform for developing, shipping, and running applications inside containers, while Kubernetes is a container orchestration tool that helps manage and scale containerized applications.

Who Are These Kubectl Cheat Sheet Commands For?
These kubectl commands are for developers, system administrators, and DevOps professionals who work with Kubernetes to manage containerized applications, whether in development, testing, or production environments.

Do You Want a Career in DevOps?
If you're interested in automation, infrastructure management, and bridging development and operations, pursuing a career in DevOps can be rewarding. Proficiency in tools like kubectl and understanding Kubernetes can significantly enhance your qualifications.

What is a StatefulSet?
A StatefulSet is a Kubernetes workload API object designed for managing stateful applications. It provides guarantees about the ordering and uniqueness of pod deployment, making it suitable for applications requiring stable identities, persistent storage, and ordered deployments.

What is a Kubernetes Manifest File?
A Kubernetes manifest file is a YAML file that defines the desired state of a Kubernetes object, such as a pod, deployment, or service. It specifies configurations, including resource specifications, labels, and containers.

What are DaemonSets?
A DaemonSet ensures that a copy of a specific pod runs on all or a subset of nodes in a Kubernetes cluster. They are typically used for background tasks like logging and monitoring, ensuring that necessary services are always running on all designated nodes.

How can I create a deployment in Kubernetes using kubectl?
To create a deployment, use the following command:

kubectl create deployment <deployment_name> --image=<container_image>

What is the kubectl command to describe a specific node in a Kubernetes cluster?
To get detailed information about a specific node, use:

kubectl describe node <node_name>

What is the kubectl command to scale deployment in Kubernetes?
To scale a deployment to a desired number of replicas, use:

kubectl scale deployment <deployment_name> --replicas=<desired_number>

What is the difference between a Deployment and a StatefulSet in Kubernetes?
A Deployment is used for stateless applications, where pods are interchangeable, while a StatefulSet is used for stateful applications that require stable network identities and persistent storage. StatefulSets maintain the order and uniqueness of pods, while Deployments do not.

What is the purpose of a Service Account in Kubernetes?
A Service Account provides an identity for processes that run in a Pod. It is used to grant permissions and manage access to the Kubernetes API and other resources, enhancing security within your cluster.

What is a ConfigMap in Kubernetes?
A ConfigMap is a key-value store used to manage configuration data separately from application code. You can use ConfigMaps to store non-confidential data that your applications need at runtime.

What does the kubectl config use-context command do?
This command sets the current context in your kubeconfig file, which specifies the cluster, user, and namespace to be used in your kubectl commands.

Authors
Anjali Udasi

Anjali Udasi

Helping to make the tech a little less intimidating. I

Contents

Do More with Less

Unlock high cardinality monitoring for your teams.