Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›Courses›Docker & Kubernetes›kubectl Cheat Sheet

Operations

kubectl Cheat Sheet

This guide provides a foundational reference for interacting with Kubernetes clusters using the command-line interface. Mastery of these commands is essential for managing container orchestration, troubleshooting deployments, and maintaining cluster state effectively. You will utilize these operations daily to inspect system resources, modify configurations, and analyze application logs in real-time environments.

Cluster Inspection and Context Management

Before interacting with a cluster, you must understand where the command is directed, as Kubernetes uses a configuration file known as kubeconfig to track clusters, users, and contexts. The 'get' and 'config' commands are your primary tools for situational awareness. By viewing the cluster-info, you confirm the API server is reachable, which is the prerequisite for all subsequent operations. Understanding contexts is vital because engineers often switch between development, staging, and production environments; failing to verify your current context can lead to catastrophic modifications in the wrong cluster. When you run a command, the client reads the active context from your local configuration, serializes the request, and sends it to the API server over HTTPS. The API server then validates your credentials against the defined role-based access control policies before executing the requested action, ensuring security and operational integrity at every step.

# Check current cluster connection
kubectl cluster-info

# View all configured contexts
kubectl config get-contexts

# Switch to a specific environment
kubectl config use-context prod-cluster-name

Resource Discovery and Inspection

To effectively operate a cluster, you must be able to list and inspect existing resources using the 'get' and 'describe' commands. While 'get' provides a concise summary of items like pods, services, or nodes, it often omits the granular details necessary for debugging. This is where 'describe' becomes invaluable; it triggers a deep inspection of a specific resource, fetching its status, events, and configuration details directly from the API server. For example, if a pod is stuck in a Pending state, 'describe' will show you the exact error messages from the scheduler or container runtime. Reasoning about these commands requires understanding that they act as interfaces to the desired state stored in etcd. When you retrieve information, you are seeing the result of the reconciliation loop where the controller ensures the actual state matches the configuration you provided, allowing you to troubleshoot effectively by comparing intended versus observed behavior.

# List all pods in the current namespace with details
kubectl get pods -o wide

# Deep dive into a specific pod's lifecycle and errors
kubectl describe pod web-server-deployment-xyz

# Get resource definitions in YAML for reuse
kubectl get service nginx-service -o yaml

Modifying Cluster State and Deployments

Modifying cluster resources can be achieved via declarative or imperative approaches. Imperative commands like 'scale' or 'annotate' modify the live object directly, which is useful for quick adjustments or emergency fixes. However, the more robust, scalable approach involves applying manifest files. When you execute 'apply', the client sends the manifest to the API server, which performs a three-way merge to reconcile your new configuration with the existing state. This method is superior for production because it allows you to store your desired state in version control, ensuring consistency. By understanding the declarative nature of these operations, you realize that you aren't just 'running' a command, but rather providing a target state that the Kubernetes control plane will diligently work to achieve. This abstraction allows you to treat infrastructure as software, enabling repeatable deployments and automated rolling updates that prevent downtime during changes.

# Apply a new configuration manifest
kubectl apply -f deployment.yaml

# Scale a deployment to handle increased traffic
kubectl scale deployment web-server --replicas=5

# Edit a resource configuration live
kubectl edit deployment web-server

Logging and Debugging Containers

Debugging applications within a distributed system requires the ability to inspect container output and execute commands inside running environments. The 'logs' command is the primary method for retrieving standard output streams from your containers; this is essential because logs are transient and vanish when a container is removed. When an application behaves unexpectedly, you should examine these logs to identify stack traces or configuration errors. Furthermore, the 'exec' command allows you to open an interactive terminal session inside a running container. This is powerful for verifying network connectivity, checking local file system contents, or confirming environment variables. It is important to note that 'exec' creates a secondary process within the container, which is useful for investigation but should not be used to 'patch' containers manually. Instead, use these insights to update your base images or deployment manifest, maintaining the integrity of the automated container lifecycle.

# Follow the logs of a specific container
kubectl logs -f pod/backend-api-v1 --tail=50

# Open a shell into a running container to debug
kubectl exec -it pod/backend-api-v1 -- /bin/sh

# Check environment variables inside a pod
kubectl exec pod/backend-api-v1 -- env

Resource Deletion and Cleanup

Cleaning up resources is as critical as creating them to prevent configuration drift and resource leaks. The 'delete' command removes objects based on names, labels, or manifest files. When you delete a resource, the API server initiates a termination sequence; for pods, this involves sending a SIGTERM signal to the process, giving it a grace period to complete pending tasks before a SIGKILL is issued. This graceful shutdown mechanism is central to the design of resilient applications. If you accidentally delete a critical service, the cluster remains functional, but users lose access, highlighting the necessity of combining deletion with namespace management. Always verify the context and labels before executing bulk deletions to avoid unintended consequences in shared environments. By mastering these cleanup procedures, you ensure that your cluster remains organized and performant, avoiding the accumulation of stale assets that can lead to confusion and degraded overall system health.

# Delete a specific pod by name
kubectl delete pod web-server-xyz

# Delete all resources defined in a specific file
kubectl delete -f deployment.yaml

# Remove all pods with a specific label
kubectl delete pods -l app=temporary-worker

Key points

  • Always verify your current cluster context before executing commands to avoid accidental changes to production environments.
  • Use the describe command for troubleshooting because it provides detailed events and status reports that get commands lack.
  • The apply command is preferred for production because it facilitates declarative configuration and version-controlled infrastructure.
  • Logs are crucial for diagnosing application errors and should be collected from containers before they are terminated.
  • The exec command allows you to enter a running container for inspection, but it should never be used to make permanent changes.
  • Resource deletion triggers a graceful shutdown process, allowing applications to finish pending tasks before exit.
  • Understanding that Kubernetes is a desired-state system helps you reason about why commands trigger asynchronous background reconciliation.
  • Label selectors are powerful tools for performing batch operations on resources based on their metadata rather than just their names.

Common mistakes

  • Mistake: Forgetting to specify the namespace. Why it's wrong: By default, commands operate in the 'default' namespace, leading to 'resource not found' errors. Fix: Always use the -n or --namespace flag or set the context namespace.
  • Mistake: Editing a live deployment directly with 'kubectl edit'. Why it's wrong: It causes configuration drift and is not reproducible. Fix: Edit the source manifest file and apply it with 'kubectl apply'.
  • Mistake: Using 'kubectl delete pod' to scale down an application. Why it's wrong: The ReplicaSet will immediately recreate the pod to maintain the desired count. Fix: Use 'kubectl scale' or update the replicas field in the deployment manifest.
  • Mistake: Overusing 'kubectl get all'. Why it's wrong: It does not actually return everything, omitting resources like Ingress or ConfigMaps. Fix: Request specific resource types like 'kubectl get pods,services,configmaps'.
  • Mistake: Running commands without verifying the current context. Why it's wrong: You might accidentally modify production clusters while intending to work in development. Fix: Run 'kubectl config current-context' before executing changes.

Interview questions

How do you view the status of all pods currently running in your default Kubernetes namespace?

To view the status of all pods in the default namespace, you use the command 'kubectl get pods'. This command is fundamental because it provides a quick overview of pod states, such as Running, Pending, or CrashLoopBackOff. Knowing the status allows you to verify if your deployments are active. For a more detailed view, including the node where the pod is hosted, you should append the wide flag: 'kubectl get pods -o wide'.

What is the command to view the logs of a specific pod, and why is this useful for debugging?

To view logs from a pod, you execute 'kubectl logs <pod-name>'. This is essential for troubleshooting because it streams the standard output of the containers within that pod directly to your terminal. If a container fails to start, the logs often contain the specific error message or stack trace needed to diagnose the issue. If the pod has multiple containers, you must use the '-c' flag to specify which container's logs you wish to inspect.

How do you retrieve the detailed configuration and status information of a Kubernetes resource, such as a deployment?

You use the command 'kubectl describe <resource-type> <resource-name>', for example, 'kubectl describe deployment my-app'. This command is far more comprehensive than 'get' because it displays the resource's events, replica sets, and current configuration settings. It is the go-to tool for identifying why a deployment is failing, as the 'Events' section at the bottom specifically highlights issues like image pull errors or resource scheduling constraints.

Compare using 'kubectl edit' versus applying a manifest file via 'kubectl apply -f'. When would you prefer one over the other?

Using 'kubectl edit' allows you to modify a running resource directly in the cluster, which is convenient for quick, temporary testing or emergency hotfixes. However, 'kubectl apply -f' is preferred for production environments because it utilizes a declarative approach. By using manifest files, you maintain version control for your infrastructure, ensure that changes are repeatable, and keep an audit trail, whereas 'kubectl edit' can lead to 'configuration drift' where the cluster state no longer matches your source-controlled code.

How can you execute a command inside a running container for diagnostic purposes?

You use the 'kubectl exec' command, typically with the '-it' flags to enable interactive terminal mode. The syntax is 'kubectl exec -it <pod-name> -- /bin/sh' or '/bin/bash'. This is critical for debugging because it lets you inspect the internal filesystem, verify environment variables, or check network connectivity from within the container's namespace. It essentially lets you 'enter' the running container to see exactly how your application is interacting with its isolated environment.

How do you perform a rolling update on a deployment when updating a container image using kubectl?

To update a deployment's image, you use 'kubectl set image deployment/<deployment-name> <container-name>=<new-image-name>'. Kubernetes performs a rolling update by default, which means it replaces old pods with new ones gradually, ensuring no downtime during the transition. You can monitor the progress of this rollout using 'kubectl rollout status deployment/<deployment-name>'. If the new image causes issues, you can immediately revert the changes using 'kubectl rollout undo deployment/<deployment-name>', which restores the previous stable version of your application.

All Docker & Kubernetes interview questions →

Check yourself

1. Which command allows you to view the logs of a pod that has multiple containers?

  • A.kubectl logs <pod-name>
  • B.kubectl logs <pod-name> --all-containers
  • C.kubectl logs <pod-name> -c <container-name>
  • D.kubectl describe pod <pod-name> --logs
Show answer

C. kubectl logs <pod-name> -c <container-name>
You must specify the container name with -c because logs are stream-specific. The first option fails if there are multiple containers, the second is not a valid flag, and the fourth describes the pod metadata rather than outputting application logs.

2. What is the primary difference between 'kubectl apply' and 'kubectl create'?

  • A.Create is for YAML, apply is for JSON
  • B.Apply is declarative, create is imperative
  • C.Create allows live patching, apply does not
  • D.Apply automatically restarts the cluster
Show answer

B. Apply is declarative, create is imperative
Apply manages the resource state declaratively by comparing the current live state with the manifest; create forces the creation of a resource and fails if it already exists. The other options are incorrect interpretations of their functional purpose.

3. You have a deployment, but changes to your Docker image tag are not reflecting. What is the most efficient command to force a redeploy?

  • A.kubectl rollout restart deployment <name>
  • B.kubectl delete deployment <name>
  • C.kubectl update deployment <name>
  • D.kubectl scale deployment <name> --replicas=0
Show answer

A. kubectl rollout restart deployment <name>
Rollout restart triggers a rolling update, effectively forcing pods to pull the new image. Deleting the deployment is destructive, 'update' is not a native command, and scaling to zero destroys the pods without ensuring the new image is pulled upon scaling back up.

4. If you need to execute a command inside a running pod to troubleshoot, which command is correct?

  • A.kubectl run <pod-name> -- <command>
  • B.kubectl exec -it <pod-name> -- <command>
  • C.kubectl attach <pod-name> -c <command>
  • D.kubectl debug <pod-name> -- <command>
Show answer

B. kubectl exec -it <pod-name> -- <command>
Exec is designed to run a process in an existing container. 'Run' creates a new pod, 'attach' connects to the main process, and 'debug' is for ephemeral containers, not standard command execution in the main container.

5. How do you temporarily expose a pod to the internet for testing purposes without creating a formal Service manifest?

  • A.kubectl port-forward pod/<name> 8080:80
  • B.kubectl expose pod/<name> --type=LoadBalancer
  • C.kubectl proxy <name>
  • D.kubectl map pod/<name> 80:8080
Show answer

A. kubectl port-forward pod/<name> 8080:80
Port-forwarding creates a tunnel from your local machine to the pod, ideal for quick testing. Expose creates a persistent Service object, proxy is for API access, and 'map' is not a valid kubectl command.

Take the full Docker & Kubernetes quiz →

← PreviousNamespacesNext →Helm Charts — Packaging K8s Apps

Docker & Kubernetes

24 lessons, free to read.

All lessons →

Track your progress

Sign in to mark lessons done, score quizzes and keep notes.

Open in the app