Kubernetes Commands You Should Learn
Kubernetes has established itself as the dominant container orchestration platform, and understanding its command-line tool kubectl is essential for anyone working with containerized applications at scale. While modern platforms like Deployxa Cloud v4.2.0 abstract much of Kubernetes complexity behind intelligent automation, knowing kubectl commands gives you powerful debugging capabilities, deeper understanding of your infrastructure, and the flexibility to work directly with Kubernetes clusters when needed. This guide covers the essential kubectl commands organized by functional category, explaining what each command does, when to use it, and practical context for real-world scenarios.
Cluster Management Commands
The kubectl cluster-info command displays essential information about your Kubernetes cluster, including the address of the control plane API server and the DNS addresses for core services. This is typically the first command you run after connecting to a new cluster to verify that your connection is working and to understand where the cluster components are accessible. It provides a quick health check that confirms you are communicating with the correct cluster and that the control plane is reachable.
The kubectl get nodes command lists all worker nodes in your cluster along with their status, roles, version, and age. This gives you an overview of the physical or virtual machines that are available to run your workloads. Node statuses include Ready, NotReady, and various maintenance states. Monitoring node health is important because unhealthy nodes cannot schedule new pods and existing pods on those nodes may be degraded. The wide output flag adds additional columns showing internal and external IP addresses, operating system, and kernel version for each node.
The kubectl describe node command followed by a node name provides a comprehensive breakdown of a specific node, including its capacity for CPU, memory, and storage, the current allocation of those resources, the pods running on that node, and any conditions or events that affect its status. This command is invaluable for capacity planning and troubleshooting node-level issues. When pods are not being scheduled due to resource constraints, describing the nodes helps you identify which nodes are under pressure and where additional capacity might be needed.
The kubectl config command manages your kubeconfig file, which stores connection details for one or more Kubernetes clusters. The get-contexts subcommand lists all available contexts, showing which cluster, user, and namespace each context points to. The use-context subcommand switches between contexts, allowing you to work with multiple clusters from the same kubectl installation. The set-context subcommand modifies context settings, such as changing the default namespace. For developers working with multiple clusters across different environments, managing contexts efficiently prevents costly mistakes like deploying to the wrong cluster.
Pod Management Commands
The kubectl get pods command lists all pods in the current namespace, showing their names, status, number of restarts, and age. Pod statuses include Running, Pending, CrashLoopBackOff, ImagePullBackOff, Completed, and others that indicate different lifecycle states. The all-namespaces flag lists pods across every namespace in the cluster, which is useful for getting a complete view of workloads running in your environment. The watch flag continuously updates the output as pod states change, providing a real-time view of cluster activity during deployments or incidents.
The kubectl describe pod command provides exhaustive details about a specific pod, including its specification, current state, events, container statuses, resource limits, mounted volumes, and network configuration. The events section at the bottom is particularly valuable for troubleshooting because it shows a chronological log of significant events such as scheduling decisions, image pulls, container starts, and termination reasons. When a pod is not behaving as expected, describing it is usually the most informative diagnostic step you can take. Understanding Kubernetes explained for developers provides the conceptual framework needed to interpret describe output effectively.
The kubectl logs command retrieves the log output from one or more containers within a pod. The container flag specifies which container to pull logs from when a pod contains multiple containers. The follow flag streams logs in real time, similar to tail functionality. The previous flag retrieves logs from a crashed container's previous instance, which is essential when debugging CrashLoopBackOff situations where the container keeps restarting. The tail and since flags let you filter log output by quantity and time. When working with multiple pods belonging to a deployment, you can use label selectors to pull logs from all matching pods simultaneously.
The kubectl exec command runs a command inside a container within a pod. This is your primary tool for interactive debugging, letting you shell into a running container to inspect the filesystem, check environment variables, test network connectivity, and run diagnostic commands. The interactive and tty flags provide a full terminal session inside the container. You can also run single commands without an interactive shell for quick checks. This command is analogous to docker exec and serves the same purpose of giving you direct access to the container environment for troubleshooting.
The kubectl port-forward command creates a network tunnel from your local machine to a port on a pod, allowing you to access services running inside your cluster as if they were running locally. This is invaluable for development and debugging because it lets you interact with internal services through localhost without exposing them publicly. You can forward to a specific pod, a service, or a deployment. The command works for any TCP port and supports multiple port mappings simultaneously, making it possible to access web interfaces, databases, and other services running inside your cluster.
Deployment Management Commands
The kubectl get deployments command lists all deployments in the current namespace, showing the desired number of replicas, the current number of available replicas, and the number of pods that are up to date. This gives you a quick summary of whether your deployments are running the expected number of instances and whether all pods have been updated to the latest deployment revision. When deployments are scaling or rolling out new versions, this command shows the progression in real time.
The kubectl rollout status command monitors the progress of a deployment rollout, showing whether the new revision is successfully replacing the old pods. It displays messages about each step of the rollout process, including pod creation, readiness checks, and old pod termination. This command is particularly useful during deployments because it gives you a clear indication of whether the rollout is progressing normally or has stalled due to issues such as failing health checks or image pull errors. It exits successfully when the rollout completes.
The kubectl rollout history command shows the revision history of a deployment, listing each revision number and the change that triggered it. The revision flag provides detailed information about a specific revision, including the pod template specification at that point. This history is essential for understanding what changed in previous deployments and for targeting specific revisions when rolling back. Each time you update a deployment, Kubernetes creates a new revision, preserving the previous configuration so you can return to it if needed.
The kubectl rollout undo command rolls back a deployment to its previous revision, replacing the current pods with pods matching the previous pod template. The to-revision flag lets you roll back to a specific revision rather than just the previous one. Kubernetes performs the rollback as a new rollout, meaning it gradually replaces the current pods with the rollback target pods, maintaining availability throughout the process. This command is one of the most important safety mechanisms in Kubernetes because it lets you quickly revert problematic deployments without needing to identify and apply the exact previous configuration manually.
Service and Networking Commands
The kubectl get services command lists all Kubernetes services in the current namespace, showing their type, cluster IP address, external IP address, and port mappings. Services provide stable network endpoints for accessing pods, which are ephemeral by nature. Understanding the different service types, including ClusterIP for internal access, NodePort for external access via node ports, and LoadBalancer for cloud-provided load balancers, is essential for designing accessible applications on Kubernetes.
The kubectl describe service command shows detailed configuration for a specific service, including its selector, which determines which pods receive traffic, its port definitions, session affinity settings, and any associated endpoints. The endpoints section shows the actual pod IPs that the service routes traffic to, which is useful for verifying that the service selector is matching the intended pods. When traffic is not reaching your application, checking the endpoints of the service is a critical debugging step because the service cannot route traffic if no endpoints are registered.
The kubectl get endpoints command lists all endpoint resources, which represent the actual pod IPs backing each service. Endpoints are automatically maintained by Kubernetes based on service selectors and pod labels. If a service shows no endpoints, it means no running pods match the selector, which could indicate a labeling mismatch, pods that are not yet ready, or pods that have all crashed. This command is a quick way to verify that services are connected to their intended pods.
ConfigMaps and Secrets Management
The kubectl get configmaps command lists all ConfigMaps in the current namespace, which store non-sensitive configuration data as key-value pairs that pods can consume as environment variables, command-line arguments, or mounted files. ConfigMaps decouple configuration from container images, allowing you to change application behavior without rebuilding images. They are fundamental to the Kubernetes philosophy of declarative, version-controlled infrastructure.
The kubectl create configmap command creates a new ConfigMap from literal values, files, or directories. The from-literal flag creates key-value pairs directly from the command line. The from-file flag reads a file and creates a key using the filename. The from-env-file flag reads an environment file format and creates corresponding ConfigMap entries. These options make it easy to create ConfigMaps from existing configuration sources without manually converting them to YAML.
The kubectl get secrets command lists all secrets in the current namespace, which store sensitive data such as passwords, API keys, and TLS certificates in an encoded format. Secrets are similar to ConfigMaps but provide additional protections, including base64 encoding and optional encryption at rest. The describe secret command shows the metadata and data keys without revealing the actual values, which is important for security when debugging in shared environments.
The kubectl create secret command creates secrets from literal values, files, or SSH keys. The generic flag creates an opaque secret from specified data. The docker-registry flag creates a secret for authenticating with a container registry, and the tls flag creates a TLS secret from a certificate and key pair. Proper secret management is a critical aspect of cloud deployment security and should follow established best practices for rotation, access control, and auditing.
Scaling and Resource Management
The kubectl scale command adjusts the number of replicas for a deployment, replica set, stateful set, or replication controller. The replicas flag specifies the desired count, and the current flag scales to match the current number of pods. This command enables manual scaling decisions when you need to respond to predictable traffic patterns or performance requirements. For automatic scaling, the Kubernetes horizontal pod autoscaler adjusts replica counts based on CPU utilization, memory usage, or custom metrics, but the scale command gives you direct manual control.
The kubectl top command shows resource usage for nodes or pods. The kubectl top pods command displays CPU and memory consumption for each pod, helping you identify resource bottlenecks and right-size your resource requests and limits. The kubectl top nodes command shows aggregate resource usage across all nodes. By default, resource metrics are provided by the metrics-server addon, which must be installed on your cluster. This command is essential for understanding how your applications consume resources and for identifying optimization opportunities.
The kubectl apply command applies configuration changes defined in YAML or JSON files to your cluster resources. It uses a server-side diff to determine what changes need to be made, making it safe to run multiple times without causing unintended side effects. This declarative approach means you describe the desired state and Kubernetes figures out how to achieve it. The filename flag specifies the configuration files, and the recursive flag applies all files in a directory. The apply command is the foundation of GitOps workflows where cluster state is driven by version-controlled configuration files.
The kubectl delete command removes resources from your cluster by type and name. You can delete individual resources, multiple resources by label selector, or all resources in a namespace. The grace-period flag sets how long Kubernetes waits before forcefully terminating the resource. The now flag sets the grace period to zero for immediate deletion. When deleting deployments, you can choose whether to also delete the pods and their associated resources using cascading delete options.
Debugging and Troubleshooting Workflows
When something goes wrong in a Kubernetes cluster, a systematic troubleshooting approach is more effective than randomly checking resources. Start with kubectl get pods to identify any pods that are not in the Running state or are showing restart counts. For any problematic pod, run kubectl describe pod to review events and conditions. Check kubectl logs for application error messages, using the previous flag if the container has restarted. Use kubectl exec to investigate the container environment directly.
Network issues are among the most common Kubernetes troubleshooting scenarios. If a service cannot reach its pods, verify endpoints with kubectl get endpoints. Check that the service selector matches pod labels. Use kubectl exec to run network tests from inside a pod, verifying DNS resolution with nslookup and connectivity with curl. If pods cannot communicate across namespaces, verify network policies are not blocking traffic. Port-forwarding with kubectl port-forward helps isolate whether issues are related to the application or the network path.
Resource-related issues often manifest as pods stuck in Pending state or being evicted. Use kubectl describe node to see resource allocation and identify nodes under pressure. Check pod resource requests and limits in the deployment specification. Use kubectl top pods to see actual resource consumption versus configured limits. Understanding the relationship between resource requests, which affect scheduling, and resource limits, which affect runtime behavior, is crucial for preventing resource contention and ensuring application stability.
When You Need Kubernetes Versus When a PaaS Is Enough
Kubernetes provides powerful capabilities for managing containerized workloads at scale, including self-healing, auto-scaling, service discovery, rolling updates, and sophisticated networking. However, this power comes with significant operational complexity. Managing your own Kubernetes cluster requires expertise in cluster administration, networking, storage, security, monitoring, and upgrade management. Even with managed Kubernetes offerings from cloud providers, you are responsible for application-level configuration, resource management, and troubleshooting.
For many development teams and organizations, the operational overhead of Kubernetes outweighs the benefits. When your primary need is to deploy web applications and APIs without managing infrastructure, modern PaaS platforms provide a dramatically simpler experience. Deployxa Cloud v4.2.0, for example, handles container orchestration, automatic scaling, SSL management, health monitoring, and intelligent routing without requiring you to write Kubernetes manifests or manage cluster infrastructure. You push code and the platform handles the rest.
Understanding Kubernetes commands remains valuable even when using a PaaS because it gives you insight into how your applications are running, helps you diagnose issues more effectively, and prepares you for situations where direct Kubernetes access is necessary. However, recognizing when Kubernetes alternatives for small teams are more appropriate is a sign of engineering maturity. The best teams choose the simplest tool that meets their requirements, reserving Kubernetes for situations where its complexity is genuinely justified by the demands of the workload.
For organizations that do operate Kubernetes clusters, kubectl proficiency is non-negotiable. Cluster operators, SRE teams, and platform engineers use these commands daily to manage deployments, troubleshoot issues, and maintain cluster health. The commands covered in this guide form the foundation of that expertise, and they provide a starting point for exploring more advanced Kubernetes features such as custom resource definitions, operators, service mesh configuration, and advanced networking policies. Whether you are directly managing clusters or working with a platform that manages them for you, understanding kubectl makes you a more effective and informed developer.