Kubernetes

Kubectl Cheat Sheet – 16 Kubernetes Commands & Objects

Kubernetes cheat sheet

🚀 Level Up Your Infrastructure Skills

You focus on building. We’ll keep you updated. Get curated infrastructure insights that help you make smarter decisions.

In this post, we list and describe each commonly used category or component of Kubernetes (K8S) with the corresponding kubectl commands for quick reference. This is perfect for anyone who works hands-on with kubectl, Kubernetes administration, or container orchestration.

kubectl is a Kubernetes command-line tool that allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs.

Kubernetes objects and kubectl command cheatsheet

1. Common options and flags

Common options in kubectl include flags that control output, namespace, resource selection, and execution behavior. These options modify how commands operate and are often used across multiple kubectl commands.

alias – Set an alias for kubectl.

alias k=kubectl
echo 'alias k=kubectl' >>~/.bashrc

-o=json Output format in JSON.

kubectl get pods -o=json

-o=yaml Output format in YAML.

kubectl get pods -o=yaml

-o=wide Output in the plain-text format with any additional information, and for pods, the node name is included.

kubectl get pods -o=wide

-n – Alias for namespace.

kubectl get pods -n=<namespace_name>

-f – Filename, directory, or URL to files to use to create a resource.

kubectl create -f ./<file name>

-l – Filter using a specified label.

kubectl logs -l name=<label name>

-h – Help for kubectl.

kubectl -h

--watch – Stream resource changes in real time.

kubectl get deployment my-deploy --watch

--grace-period – Set termination grace period in seconds.

kubectl delete pod my-pod --grace-period=10

--force – Force actions like deletion.

kubectl delete pod my-pod --grace-period=0 --force

Pro tip: Use kubectl explain <resource> to view API documentation for any Kubernetes resource directly from the CLI.

2. Configuration files commands

In Kubernetes, configuration files (often called manifest files or YAML files) define the desired state of cluster resources using a declarative format. These files tell Kubernetes what to create, modify, or manage, such as pods, deployments, services, or volumes.

Each file typically contains:

  • An apiVersion to specify the Kubernetes API version
  • A kind to define the type of resource (e.g., Deployment, Service)
  • metadata for naming and labeling
  • A spec section that outlines the configuration details (like container images, replicas, or ports)

The core command to apply a Kubernetes configuration file is:

kubectl apply -f <configuration file>

This command creates or updates the resources defined in the YAML file to match the desired state. 

kubectl create -f <configuration file>  – Create objects.

kubectl create -f <configuration file directory> – Create objects in all manifest files in a directory.

kubectl create -f <‘url’> – Create objects from a URL.

kubectl get -f <configuration file> – Retrieve the status of the resources.

kubectl diff -f <configuration file> – Show differences between the live cluster state and the config file.

kubectl delete -f <configuration file> – Delete an object.

Read more about kubectl apply vs. kubectl create – What’s the Difference.

3. Cluster management and context commands

Cluster management in Kubernetes refers to operations that retrieve or manipulate information about the cluster itself, such as nodes, namespaces, roles, and API resources. Cluster context defines access to a specific Kubernetes cluster, including user credentials and the namespace.

kubectl cluster-info – Display endpoint information about the master and services in the cluster.

kubectl version – Display the Kubernetes version running on the client and server.

kubectl config view – Get the cluster configuration.

kubectl config view -o jsonpath='{.users[*].name}' – Get a list of users.

kubectl config current-context – Display the current context.

kubectl config get-contexts – Display a list of contexts.

kubectl config set-context <name> – Update or create a context entry in kubeconfig file, defining cluster access settings like the cluster, namespace, and user.

kubectl config use-context <cluster name> – Set the default context.

kubectl api-resources – List the available API resources.

kubectl api-versions – List the available API versions.

-A – List pods, services, daemonsets, deployments, replicasets, statefulsets, jobs, and CronJobs in all namespaces, not custom resource types. Note the alias for --all-namespaces is -A

kubectl get all --all-namespaces

4. Daemonsets commands

A Kubernetes DaemonSet ensures that a specific pod runs on all (or selected) nodes in a cluster. As nodes are added or removed, the DaemonSet automatically adds or deletes the pods accordingly.

kubectl apply -f <daemonset_name>Create a DaemonSet.

kubectl get daemonset – List one or more Daemonsets.

kubectl get daemonsets --all-namespaces – List DaemonSets across all namespaces.

kubectl get daemonset <daemonset_name> -o yaml – YAML output of a DaemonSet (for backup or inspection)

kubectl edit daemonset <daemonset_name> – Edit and update the definition of one or more Daemonsets.

kubectl delete daemonset <daemonset_name> – Delete a Daemonset.

kubectl rollout daemonset – Manage the rollout of a Daemonset.

kubectl describe ds <daemonset_name> -n <namespace_name> – Display the detailed state of Daemonsets within a namespace.

5. Deployment commands

A Kubernetes Deployment is a controller that manages the lifecycle of application Pods by declaratively defining the desired state and ensuring the system continuously aligns with it.

A Deployment specifies how many Pods should run, what container images they use, and how they should be updated. It works with ReplicaSets to ensure the correct number of pod replicas are always running. The Deployment Controller monitors the cluster and automatically replaces or scales Pods as needed to match the defined state.

kubectl get deployment – List one or more Deployments.

kubectl describe deployment <deployment_name> – Display the detailed state of one or more Deployments.

kubectl edit deployment <deployment_name> – Edit and update the definition of one or more Deployments on the server.

kubectl create deployment <deployment_name> – Create a new Deployment.

kubectl delete deployment <deployment_name> – Delete Deployments.

kubectl rollout status deployment <deployment_name> – See the rollout status of a Deployment.

kubectl set image deployment/<deployment name> <container name>=image:<new image version> – Perform a rolling update (K8S default), set the image of the container to a new version for a particular Deployment.

kubectl rollout undo deployment/<deployment name> – Roll back a previous Deployment.

kubectl replace --force -f <configuration file> – Perform a replace Deployment: Force replace, delete, and then re-create the resource.

kubectl scale deployment <deployment name> --replicas=<n> – Manually scale the number of pod replicas in a Deployment.

Read more about Kubernetes deployment strategies: Different Types of Kubernetes Deployment Strategies (Examples)

6. Events commands

A Kubernetes event is a record of a state change or occurrence within the cluster, typically used for debugging or auditing. Events are generated by the Kubernetes system and components such as the scheduler, controllers, or kubelet.

kubectl get events – List recent events for all resources in the system.

kubectl get events --field-selector type=Warning – List Warnings only.

kubectl get events --sort-by=.metadata.creationTimestamp – List events sorted by timestamp.

kubectl get events --field-selector involvedObject.kind!=Pod – List events but exclude Pod events.

kubectl get events --field-selector involvedObject.kind=Node, involvedObject.name=<node_name> – Pull events for a single node with a specific name.

kubectl get events --field-selector type!=Normal – Filter out normal events from a list of events.

7. Log commands

Kubernetes logs refer to the output generated by containers, pods, nodes, and cluster components, used to monitor and debug applications running within a Kubernetes environment.

kubectl logs <pod_name> – Print the logs for a pod.

kubectl logs --since=6h <pod_name> – Print the logs for the last 6 hours for a pod.

kubectl logs --tail=50 <pod_name> – Get the most recent 50 lines of logs.

kubectl logs -f <pod_name> – Print the logs for a pod and follow new logs.

kubectl logs -c <container_name> <pod_name> – Print the logs for a container in a pod.

kubectl logs <pod_name> pod.log – Output the logs for a pod into a file named “pod.log”.

kubectl logs --previous <pod_name> – View the logs for a previously failed pod.

kubectl logs --timestamps <pod_name> – Include timestamps with each log line.

8. Namespaces commands

A Kubernetes namespace is a logical partition within a cluster that isolates groups of resources for organizational or access control purposes. Each namespace maintains its own scope for namespaced resources such as Pods, Services, Deployments, and ConfigMaps.

kubectl create namespace <namespace_name> – Create a namespace.

kubectl get namespacesList all namespaces in the cluster (note the plural form).

kubectl get namespace <namespace_name> – List one or more namespaces.

kubectl describe namespace <namespace_name> – Display the detailed state of one or more namespaces.

kubectl delete namespace <namespace_name> – Delete a namespace.

kubectl edit namespace <namespace_name> – Edit and update the definition of a namespace.

kubectl top namespace <namespace_name> – Display Resource (CPU/Memory/Storage) usage for a namespace.

kubectl api-resources --namespaced=trueShow which Kubernetes resource types are namespace-scoped vs. cluster-scoped.

9. Nodes commands

A Kubernetes node is a physical or virtual machine that runs containerized workloads managed by the Kubernetes control plane. It hosts the necessary components to execute Pods, which are the smallest deployable units in Kubernetes.

Each node includes key components

Nodes are orchestrated by the control plane, which schedules and maintains workloads across the cluster.

kubectl taint node <node_name> – Update the taints on one or more nodes.

kubectl get node – List one or more nodes.

kubectl delete node <node_name> – Delete a node or multiple nodes.

kubectl top node <node_name> – Display Resource usage (CPU/Memory/Storage) for nodes.

kubectl get pods -o wide | grep <node_name> – Pods running on a node

kubectl annotate node <node_name> – Annotate a node.

kubectl cordon node <node_name> – Mark a node as unschedulable.

kubectl uncordon node <node_name> – Mark node as schedulable.

kubectl drain node <node_name> – Drain a node in preparation for maintenance.

kubectl label node – Add or update the labels of one or more nodes.

kubectl describe node <node_name> – Shows detailed information about a node, including labels, taints, conditions, and allocated resources.

kubectl edit node <node_name> – Open the node configuration in your default editor for manual changes, such as editing labels or taints.

kubectl patch node <node_name> -p <patch> – Apply a partial update to a node’s configuration using a JSON or YAML patch.

10. Pods commands

A Kubernetes pod is the smallest deployable unit in Kubernetes, consisting of one or more containers that share the same network namespace and storage volumes. 

All containers in a pod run on the same node and are tightly coupled. Pods are ephemeral by default. If a pod fails, Kubernetes can create a new instance; however, it will have a different IP unless managed by higher-level abstractions, such as Deployments or StatefulSets.

kubectl get pod – List one or more pods.

kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' – List pods Sorted by Restart Count.

kubectl get pods --field-selector=status.phase=Running – Get all running pods in the namespace.

kubectl delete pod <pod_name> – Delete a pod.

kubectl describe pod <pod_name> – Display the detailed state of a pod.

kubectl create pod <pod_name> – Create a pod.

kubectl exec <pod_name> -c <container_name> <command> – Execute a command against a container in a pod. Read more: Using Kubectl Exec: Connect to Your Kubernetes Containers

kubectl exec -it <pod_name> /bin/sh – Get an interactive shell on a single-container pod.

kubectl top pod – Display Resource usage (CPU/Memory/Storage) for pods.

kubectl annotate pod <pod_name> <annotation> – Add or update the annotations of a pod.

kubectl label pods <pod_name> new-label=<label name> – Add or update the label of a pod.

kubectl get pods --show-labels – Get pods and show labels.

kubectl port-forward <pod name> <port number to listen on>:<port number to forward to> – Listen on a port on the local machine and forward to a port on a specified pod.

kubectl logs <pod_name> – View logs for the main container in a pod. For multi-container pods, add -c <container_name>.

kubectl get pod <pod_name> -o yaml – Output the full YAML definition of a pod for inspection or reuse.

kubectl wait --for=condition=Ready pod/<pod_name> – Block until the pod is ready. Useful in automation scripts.
kubectl cp <pod_name>:<path_in_pod> <local_path> – Copy files from a pod to your local system, or vice versa.

kubectl replace -f <pod.yaml> – Replace a pod using a modified YAML definition (often used in CI/CD workflows).

Grow your Kubernetes expertise with detailed guides and tutorials on the Spacelift blog.

11. Replication Controllers commands

A Replication Controller in Kubernetes ensures that a specified number of pod replicas are running at any given time. It monitors pods and automatically replaces any that fail or are terminated, maintaining the desired state.

Note: ReplicationControllers have been largely replaced by Deployments, which offer more advanced features, including rolling updates and rollbacks.

kubectl get rc – List the replication controllers.

kubectl get rc --namespace=”<namespace_name>” – List the replication controllers by namespace.

12. ReplicaSets commands

A Kubernetes ReplicaSet ensures a specified number of identical pod replicas are running at all times. If a pod fails or is deleted, the ReplicaSet automatically creates a new one to maintain the desired count.

It’s commonly managed indirectly through Deployments, which handle rolling updates and versioning while using ReplicaSets under the hood.

kubectl get replicasets – List ReplicaSets.

kubectl describe replicasets <replicaset_name> – Display the detailed state of one or more ReplicaSets.

kubectl scale --replicas=[x] – Scale a ReplicaSet.

13. Secrets

A Kubernetes Secrets object stores sensitive data, such as passwords, tokens, or SSH keys, in base64-encoded form. It lets you keep this data separate from application code and make it available to pods securely through environment variables or mounted volumes. 

kubectl create secret – Create a secret.

kubectl get secrets – List secrets.

kubectl describe secrets – List details about secrets.

kubectl delete secret <secret_name> – Delete a secret.

14. Services

A Kubernetes Service is an abstraction that defines a stable network endpoint for a set of Pods. Since Pods can be created and destroyed dynamically, a Service ensures that clients can reliably reach them using a consistent IP and DNS name. It automatically load balances traffic across the selected Pods using label selectors.

kubectl get services – List one or more services.

kubectl describe services – Display the detailed state of a service.

kubectl expose deployment [deployment_name] – Expose a replication controller, service, deployment, or pod as a new Kubernetes service.

kubectl edit services – Edit and update the definition of one or more services.

15. Service Accounts commands

Service Accounts in Kubernetes are special accounts used by pods to authenticate with the Kubernetes API server and other services within the cluster. They allow workloads to access resources without using user credentials.

By default, every pod is assigned a Service Account, typically with default in its namespace. Each Service Account has an associated secret that includes a token used for API access, which is mounted into the pod. Access permissions are controlled through Role-Based Access Control (RBAC), which binds roles to Service Accounts to define what actions they can perform.

kubectl get serviceaccounts – List service accounts.

kubectl describe serviceaccounts – Display the detailed state of one or more service accounts.

kubectl replace serviceaccount – Replace a service account.

kubectl delete serviceaccount <service_account_name> – Delete a service account.

16. StatefulSet commands

A StatefulSet in Kubernetes is a controller used to manage stateful applications, where each pod needs a stable identity and persistent storage. Unlike Deployments, StatefulSets maintain a consistent network identity and stable, ordered pod creation and termination.

StatefulSets assign each pod a unique, persistent hostname (e.g., pod-0, pod-1) and ensure that these identities are maintained across rescheduling. 

They also work with PersistentVolumeClaims to provide stable storage that remains even if the pod is deleted. This is critical for workloads such as databases, queues, or clustered systems that rely on ordered startup and identity.

kubectl get statefulset – List StatefulSet

kubectl delete statefulset/<stateful_set_name> --cascade=false – Delete StatefulSet only (not pods).

kubectl describe statefulset <stateful_set_name> – Describe a StatefulSet (inspect configuration and status).

kubectl scale statefulset <stateful_set_name> --replicas=<count> – Scale a StatefulSet (manually set replica count).

kubectl edit statefulset <stateful_set_name> – Edit a StatefulSet (modify YAML in-place).

kubectl patch statefulset <stateful_set_name> -p '{"spec":{"template":{"metadata":{"annotations":{"date":"'"$(date +%s)"'"}}}}}' – Force rolling update by patching the pod template (e.g., update annotations).

kubectl get pods -l app=<label_of_statefulset> View pods managed by a StatefulSet (by label selector).

Why use Spacelift with Kubernetes?

If you need help managing your Kubernetes projects, consider Spacelift. It brings with it a GitOps flow, so your Kubernetes Deployments are synced with your Kubernetes Stacks, and pull requests show you a preview of what they’re planning to change. 

With Spacelift, you get:

  • Policies to control what kind of resources engineers can create, what parameters they can have, how many approvals you need for a run, what kind of task you execute, what happens when a pull request is open, and where to send your notifications
  • Stack dependencies to build multi-infrastructure automation workflows with dependencies, having the ability to build a workflow that can combine Terraform with Kubernetes, Ansible, and other infrastructure-as-code (IaC) tools such as OpenTofu, Pulumi, and CloudFormation.
  • Self-service infrastructure via Blueprints, enabling your developers to do what matters – developing application code while not sacrificing control
  • Creature comforts such as contexts (reusable containers for your environment variables, files, and hooks), and the ability to run arbitrary code
  • Drift detection and optional remediation

If you want to learn more about Spacelift, create a free account today or book a demo with one of our engineers.

Key points

kubectl is the command-line tool for interacting with Kubernetes clusters. It allows you to deploy applications, inspect and manage cluster resources, and troubleshoot issues. Cheat sheets are useful for streamlining daily operations and remembering syntax.

The most flexible CI/CD automation tool

Spacelift is an alternative to using homegrown solutions on top of a generic CI. It helps overcome common state management issues and adds several must-have capabilities s for infrastructure management.

Start free trial

Frequently asked questions

  • What are the major components of Kubernetes?

    Kubernetes consists of control plane and node components that together manage containerized applications. 

    The control plane includes the API server, etcd for state storage, the scheduler for pod placement, and controller managers for maintaining desired states. Nodes run kubelet to manage containers, kube-proxy for networking, and a container runtime such as containerd or CRI-O.

  • How to list and filter Kubernetes resources?

    To list and filter Kubernetes resources, use kubectl get command with optional flags like -l (label selector), –field-selector to narrow results, and –all-namespaces to list across all namespaces

  • How to inspect and debug a Pod?

    Start with kubectl get pods to check pod status, then use kubectl describe pod <pod-name> for detailed information about the pod lifecycle, events, and failure reasons. Use kubectl logs <pod-name> to view stdout/stderr output from containers. If the pod has multiple containers, specify one using -c <container-name>

    For real-time debugging or manual inspection, use kubectl exec -it <pod-name> -- /bin/sh or /bin/bash to access the container shell.

    If the pod is in CrashLoopBackOff or Pending, check related events, image pull issues, or resource limits. Inspecting the underlying node (kubectl describe node) may also reveal scheduling or runtime problems.

  • How to switch clusters and namespaces?

    To switch clusters and namespaces in Kubernetes, use the kubectl config command with appropriate flags.

Kubernetes Commands Cheat Sheet

Grab our ultimate cheat sheet PDF

for all the kubectl commands you need.

k8s book
Share your data and download the cheat sheet