Introduction / Why This Is Needed
kubectl is the primary command-line tool for managing Kubernetes clusters. This cheat sheet compiles the most essential commands for daily tasks: working with pods, deployments, services, configs, and secrets. After studying it, you'll be able to perform standard operations quickly without constantly searching through documentation.
Requirements / Preparation
- Installed kubectl (version 1.20 or higher recommended)
- An available Kubernetes cluster and a configured kubeconfig file
- Basic understanding of Kubernetes resources (pods, deployments, services, etc.)
Step 1: Setting Up Cluster Connection
Before starting, ensure kubectl is configured to connect to the correct cluster.
Check current configuration:
kubectl config view
View available contexts:
kubectl config get-contexts
Switch to a different context:
kubectl config use-context <context-name>
Check cluster connection:
kubectl cluster-info
If the command returns cluster information, the connection is established.
Step 2: Managing Pods
Pods are the smallest deployable units in Kubernetes.
Create a pod from a YAML manifest:
kubectl apply -f pod.yaml
View pods in the current namespace:
kubectl get pods
View pods in all namespaces:
kubectl get pods --all-namespaces
Detailed information about a pod:
kubectl describe pod <pod-name>
Delete a pod:
kubectl delete pod <pod-name>
Start an interactive shell in a pod's container:
kubectl exec -it <pod-name> -- /bin/bash
# For the default container. If the pod has multiple containers, specify -c <container-name>
View pod logs:
kubectl logs <pod-name>
# For a multi-container pod: kubectl logs <pod-name> -c <container-name>
Step 3: Managing Deployments and Services
Deployments manage pods, providing updates and scaling. Services provide network access to pods.
Create a deployment:
kubectl create deployment <deployment-name> --image=<container-image>
View deployments:
kubectl get deployments
Scale a deployment:
kubectl scale deployment <deployment-name> --replicas=3
Update the container image in a deployment:
kubectl set image deployment/<deployment-name> <container-name>=<new-image>
Create a service for a deployment (NodePort type):
kubectl expose deployment <deployment-name> --type=NodePort --port=80
View services:
kubectl get services
Step 4: Working with Configs and Secrets
ConfigMap and Secret allow you to pass configuration and confidential data into pods.
Create a ConfigMap from a literal:
kubectl create configmap <configmap-name> --from-literal=key=value
Create a ConfigMap from a file:
kubectl create configmap <configmap-name> --from-file=/path/to/file
View a ConfigMap:
kubectl get configmap <configmap-name> -o yaml
Create a Secret (generic type):
kubectl create secret generic <secret-name> --from-literal=username=admin --from-literal=password='s3cr3t'
View a Secret:
kubectl get secret <secret-name> -o yaml
Step 5: Monitoring and Debugging
Commands for diagnosing problems.
View events (sorted by time):
kubectl get events --sort-by='.lastTimestamp'
Start a temporary pod for debugging (e.g., with the busybox image):
kubectl run debug --rm -i --tty --image=busybox -- /bin/sh
# The pod will be deleted after exit (--rm flag)
View resource usage (requires metrics-server):
kubectl top pods
kubectl top nodes
Check logs of system components (if accessible):
kubectl logs -n kube-system <component-pod-name>
Result Verification
This cheat sheet does not require result verification in the traditional sense. Ensure all listed commands execute without errors on your cluster. For practice, create test resources in a separate namespace.
Potential Issues
Authentication/Authorization errors:
- "Unauthorized" or "Forbidden": check your kubeconfig and RBAC permissions.
Resource not found:
- Ensure the resource exists and you've specified the correct name and namespace. Use
kubectl get <resource> --all-namespacesto search.
Pod in Pending state:
- Insufficient resources on nodes, or no suitable nodes due to taints/tolerations or nodeSelector. Check events:
kubectl describe pod <pod-name>.
Pod in CrashLoopBackOff state:
- The application inside the container is crashing. Check logs:
kubectl logs <pod-name> --previous(for the previous instance) andkubectl describe pod <pod-name>.
Incorrect context or namespace:
- Check the current context:
kubectl config current-contextand namespace:kubectl config view --minify | grep namespace. Switch if necessary.
"field is immutable" error:
- Some resource fields cannot be changed (e.g., name). Delete and recreate the resource.
"the server doesn't have a resource type ..." error:
- Possibly using an outdated API version. Check available resources:
kubectl api-resources. Specify the correct API version in the YAML.
"image pull back off" error:
- Image not found or no permission to pull it. Check the image name and configure imagePullSecrets.
Service not providing access:
- For NodePort, ensure the port is open on the node. For LoadBalancer, check that the provider created the load balancer.
PersistentVolumeClaim in Pending state:
- No suitable PersistentVolume. Check if PVs exist or configure dynamic provisioning via a StorageClass.
No metrics for kubectl top:
- Ensure metrics-server is installed and running.
Pod logs are empty:
- The application may not write to stdout/stderr. Check the application's configuration.
"error: You must be logged in to the server":
- Check your kubeconfig. The token may have expired.
DNS issues:
- Check that CoreDNS (or another DNS addon) is running. Check DNS configuration in pods.
Error creating resource from YAML:
- Check YAML syntax. Use
kubectl apply --validate=trueorkubectl create --dry-run=client.
Quota exceeded (ResourceQuota):
- Check quotas:
kubectl describe quota. Delete unused resources or request a quota increase.
Issues updating ConfigMap/Secret in pods:
- Pods do not update automatically. Restart the pod (e.g., via a rolling update of the deployment).
"error: a container name must be specified for pod ...":
- The pod has multiple containers; specify the container name with the
-cflag.
"error: the connection to the server ... was refused":
- The API server is unreachable. Check that the cluster is running and the kubeconfig is correct.
"error: unknown flag":
- Your kubectl version may be too old. Update kubectl.
Autocompletion issues:
- Install the autocompletion plugin for your shell.
"error: no matches for kind ... in version ...":
- Specify the correct API version in the YAML manifest.
Issues with temporary files (emptyDir):
- emptyDir exists only while the pod runs. Use PersistentVolume for permanent storage.
"secret ... not found" error:
- Ensure the Secret exists in the same namespace.
"field is immutable" error when changing annotations:
- Some annotations are also immutable. Delete and recreate the resource.
Cannot access a NodePort service from the host:
- Ensure you are using the node's IP and the NodePort, and that the firewall allows traffic.
LoadBalancer issues in the cloud:
- Check that your cloud provider supports LoadBalancer and that your account has the necessary permissions.
"error: the server doesn't have a resource type "svc"" error:
- Correct:
kubectl get svc(abbreviation) orkubectl get services.
kubectl command hangs:
- Increase the timeout:
kubectl --request-timeout=30s ....
Issues with resource names:
- Names must conform to DNS naming conventions (lowercase letters, digits, hyphens, up to 253 characters).
"metadata.annotations: Too long" error:
- Annotations have a size limit (usually 256KB). Reduce the size.
Cannot create a namespace:
- Check permissions. You need rights to create namespaces (e.g., a role with
createon namespaces).
Cluster upgrade issues:
- Before upgrading, ensure all pods are running and there are no blocking issues. Follow the upgrade instructions for your distribution.
"error: the server doesn't have a resource type "ingress"" error:
- Install an Ingress controller and ensure the Ingress API is enabled (networking.k8s.io/v1).
Storage issues (PersistentVolumeClaim in Pending):
- Check for a suitable PersistentVolume. You may need to create a PV manually or use a StorageClass.
"failed to start container" error on kubectl run:
- Check if the image exists and is accessible (correct name, tag, repository).
Selector issues in services:
- Ensure the service's selectors match the pod's labels.
"error: unable to read URL" error on kubectl apply:
- Check that the URL is accessible and you have read permissions.
"error: no matches for kind "CronJob" in version "batch/v1beta1"" error:
- Ensure the correct API version is specified in the YAML manifest (batch/v1 for CronJob) and that the cluster supports it.
CronJob issues:
- Check that the CronJob exists and the schedule is correct (Cron format). View events:
kubectl describe cronjob <name>.
Issues updating ConfigMap/Secret in pods without restarting:
- Some applications may reload configs, but usually a pod restart is required. Use a rolling update of the deployment.
"field is immutable" error when changing a resource name:
- A resource's name cannot be changed. Delete and recreate the resource.
Quota issues on pod count per namespace:
- Check ResourceQuota. You may need to increase the quota or delete unused pods.
"error: the server doesn't have a resource type "poddisruptionbudget"" error:
- Use
policy/v1beta1(deprecated) orpolicy/v1(if available). Check the cluster's API version.
NetworkPolicy issues:
- Ensure NetworkPolicy allows the traffic you need. By default, all traffic is allowed if no policies exist.
"error: the server doesn't have a resource type "resourcequotas"" error:
- Correct name:
resourcequota(singular) orresourcequotas(plural). Usekubectl get resourcequota.
Service name and DNS issues:
- The service name must be a valid DNS name (lowercase letters, digits, hyphens). Inside the cluster, the service is reachable at
<service-name>.<namespace>.svc.cluster.local.
"error: the server doesn't have a resource type "horizontalpodautoscaler"" error:
- Ensure metrics-server is installed and the HPA API is enabled (autoscaling/v2). Check:
kubectl api-versions | grep autoscaling.
Autoscaling (HPA) issues:
- Check that metrics-server is running and providing metrics. Ensure the deployment has resource requests (requests) set for containers.
"error: the server doesn't have a resource type "mutatingwebhookconfiguration"" error:
- Use
admissionregistration.k8s.io/v1(or an older version). Check available API versions.
ValidatingWebhookConfiguration or MutatingWebhookConfiguration issues:
- Check that the webhook is accessible (certificate, URL) and returns the correct HTTP status (200). View events:
kubectl get events --all-namespaces.
"error: the server doesn't have a resource type "priorityclass"" error:
- Use
scheduling.k8s.io/v1. Check that PriorityClass exists.
PriorityClass issues:
- Check that PriorityClass exists and that
priorityClassNameis specified in the pod. Ensure the priority value is correct.
"error: the server doesn't have a resource type "runtimeclass"" error:
- Use
node.k8s.io/v1. Check that RuntimeClass exists and that nodes support the specified runtime handler.
RuntimeClass issues:
- Check that RuntimeClass exists and that
runtimeClassNameis specified in the pod. Ensure the corresponding runtime (e.g., containerd with containerd-shim) is installed on nodes.
"error: the server doesn't have a resource type "storageversion"" error:
- This is an internal Kubernetes resource; usually no intervention is needed. Storage version migration issues can arise during cluster upgrades. Check controller logs.
"error: the server doesn't have a resource type "csistoragecapacity"" error:
- Use
storage.k8s.io/v1. This is part of CSI (Container Storage Interface). Ensure the CSI driver supports capacity reporting.
CSI driver and storage capacity issues:
- Check that the CSI driver is installed and supports reported capacity. View events:
kubectl get csinodeandkubectl describe csinode.
"error: the server doesn't have a resource type "volumeattributesclass"" error:
- Use
storage.k8s.io/v1. This resource is for volume attributes in CSI. Ensure VolumeAttributesClass exists and the driver supports it.
VolumeAttributesClass issues:
- Check that VolumeAttributesClass is created and that
volumeAttributesClassis specified in the PersistentVolumeClaim (if required).
"error: the server doesn't have a resource type "csidriver"" error:
- Use
storage.k8s.io/v1. CSIDriver registers a CSI driver in the cluster. Check that CSIDriver exists:kubectl get csidriver.
CSIDriver issues:
- If CSIDriver is not created, volumes using this driver cannot be attached. Install the CSI driver according to the provider's documentation.
"error: the server doesn't have a resource type "csinode"" error:
- Use
storage.k8s.io/v1. CSINode represents a node with a CSI driver. Check:kubectl get csinode.
CSINode issues:
- If CSINode is missing, the CSI driver is not deployed on the node. Install the CSI driver on all nodes.
"error: the server doesn't have a resource type "volumeattachment"" error:
- Use
storage.k8s.io/v1. VolumeAttachment manages volume attachment to a node. Check:kubectl get volumeattachment.
VolumeAttachment issues:
- If VolumeAttachment is in Pending state, the volume cannot be attached. Check CSI driver logs and volume availability.
"error: the server doesn't have a resource type "volumesnapshotclass"" error:
- Use
snapshot.storage.k8s.io/v1. VolumeSnapshotClass defines the driver for snapshots. Check:kubectl get volumesnapshotclass.
VolumeSnapshotClass issues:
- Ensure VolumeSnapshotClass exists and that the CSI driver supports snapshotting.
"error: the server doesn't have a resource type "volumesnapshotcontent"" error:
- Use
snapshot.storage.k8s.io/v1. VolumeSnapshotContent is the actual snapshot. Check:kubectl get volumesnapshotcontent.
VolumeSnapshotContent issues:
- If VolumeSnapshotContent is not in Ready state, the snapshot is not ready. Check events and CSI driver logs.
"error: the server doesn't have a resource type "volumesnapshot"" error:
- Use
snapshot.storage.k8s.io/v1. VolumeSnapshot is a request to create a snapshot. Check:kubectl get volumesnapshot.
VolumeSnapshot issues:
- If VolumeSnapshot does not transition to Ready state, check VolumeSnapshotClass and permissions to create snapshots.