Kubernetes Basics: Common kubectl Commands Explained

Kubernetes Basics: Common kubectl Commands Explained
Managing Kubernetes clusters doesn’t have to feel overwhelming. This kubectl tutorial breaks down the essential kubernetes basics every developer and DevOps engineer needs to master their daily container orchestration tasks.
You’ll learn the most important kubectl commands for checking cluster health, handling kubernetes pod management tasks like kubectl get pods, and managing deployments. We’ll also cover kubernetes service discovery techniques and kubectl troubleshooting methods that help you quickly diagnose and fix issues.
Whether you’re running your first pod or scaling production workloads, these kubernetes deployment commands and kubectl configuration tips will streamline your workflow. We’ll focus on practical kubernetes resource monitoring techniques and real-world scenarios you’ll encounter when working with clusters.
By the end, you’ll have a solid command reference for pod operations, service networking, and resource management that makes Kubernetes feel less intimidating and more like a powerful tool in your toolkit.
Essential kubectl Commands for Cluster Information

View cluster status and health metrics
Getting a quick overview of your Kubernetes cluster’s health starts with kubectl cluster-info, which shows your cluster endpoints and services. The kubectl get componentstatuses command reveals the status of core cluster components like the scheduler, controller-manager, and etcd. For deeper health insights, use kubectl get nodes to check node conditions and kubectl top nodes to monitor resource usage across your cluster.
Check available nodes and their resources
The kubectl get nodes -o wide command provides comprehensive node information including IP addresses, operating systems, and container runtime versions. To dive deeper into resource allocation, kubectl describe node <node-name> shows detailed capacity, allocatable resources, and current pod assignments. The kubectl top nodes command displays real-time CPU and memory consumption, helping you identify resource bottlenecks and plan workload distribution effectively.
Access cluster configuration details
Your cluster configuration lives in the kubeconfig file, accessible through kubectl config view to see current contexts and clusters. Switch between different clusters using kubectl config use-context <context-name> and check your current context with kubectl config current-context. The kubectl config get-contexts command lists all available contexts, making it easy to manage multiple Kubernetes environments from a single machine.
Monitor API server connectivity
Testing API server connectivity is straightforward with kubectl version, which shows both client and server versions while confirming communication. The kubectl api-resources command lists all available resource types your cluster supports, while kubectl api-versions displays supported API versions. If you’re experiencing connectivity issues, kubectl cluster-info dump generates comprehensive diagnostic information that’s invaluable for troubleshooting network or authentication problems.
Pod Management Commands for Daily Operations

Create and deploy new pods efficiently
Managing pod deployment involves several kubectl commands that streamline container orchestration. Use kubectl run nginx --image=nginx --port=80 to quickly spin up a single pod, or deploy from YAML files using kubectl apply -f pod.yaml for complex configurations. The kubectl create command offers another approach for creating pods directly from the command line with specific parameters.
List and filter pods across namespaces
The kubectl get pods command serves as your primary tool for kubernetes pod management across different environments. Add --all-namespaces to view pods system-wide, or use -n <namespace> to target specific namespaces. Filter results with label selectors like kubectl get pods -l app=frontend or check pod status with --field-selector=status.phase=Running to quickly identify running containers.
Delete pods and handle graceful shutdowns
Pod deletion requires careful consideration of running workloads and graceful termination periods. Execute kubectl delete pod <pod-name> for standard removal, or use --grace-period=0 --force for immediate termination when necessary. Monitor deletion progress with kubectl get pods --watch and ensure proper cleanup by verifying associated resources like services and persistent volumes are handled appropriately.
Service Discovery and Networking Commands

Expose Applications Through Service Creation
Creating services in Kubernetes makes your applications accessible across the cluster. The kubectl expose command quickly turns your pods into accessible services. For example, kubectl expose pod my-app --port=8080 --target-port=80 --type=ClusterIP creates an internal service, while kubectl expose deployment my-app --type=LoadBalancer --port=80 makes your app available externally.
You can also create services declaratively using YAML files with kubectl apply -f service.yaml. This approach gives you more control over service specifications like selectors, ports, and service types. The three main service types are ClusterIP for internal communication, NodePort for external access through node IPs, and LoadBalancer for cloud-based external access.
View Service Endpoints and Port Configurations
The kubectl get services command shows all services with their cluster IPs, external IPs, and port mappings. Add -o wide for detailed output including selectors and endpoints. For deeper inspection, kubectl describe service my-service reveals comprehensive information about endpoints, port configurations, and associated pods.
Use kubectl get endpoints to see which pods are backing your services. This command helps verify that your service selectors are correctly matching pod labels. When troubleshooting connectivity issues, checking endpoints ensures your service can find the target pods and route traffic properly.
Test Connectivity Between Services
Testing service connectivity requires running diagnostic commands inside the cluster. The kubectl exec command lets you access running pods for network testing: kubectl exec -it my-pod -- curl http://my-service:8080. This approach tests internal service communication using cluster DNS resolution.
For comprehensive network testing, deploy a temporary pod with networking tools: kubectl run test-pod --image=busybox --rm -it -- sh. From this pod, you can test DNS resolution with nslookup my-service and check connectivity using wget or telnet commands to verify service accessibility.
Manage Ingress Rules and External Access
Ingress controllers manage external HTTP/HTTPS access to services. Create ingress resources using kubectl apply -f ingress.yaml to define routing rules, hostnames, and TLS configurations. The kubectl get ingress command shows all ingress resources with their hosts and backend services.
Monitor ingress status with kubectl describe ingress my-ingress to check rule configurations and controller events. Use kubectl get ingress -o yaml for complete configuration details. When troubleshooting external access issues, verify that your ingress controller is running with kubectl get pods -n ingress-nginx and check service endpoints match your ingress backend configurations.
Resource Monitoring and Troubleshooting Commands

Check resource usage and performance metrics
Monitoring your cluster’s health starts with checking resource consumption. The kubectl top command reveals CPU and memory usage across nodes and pods, helping you spot bottlenecks before they impact performance.
View detailed pod and container logs
When applications misbehave, logs provide the first clues. Use kubectl logs to examine container output, add -f for real-time streaming, or --previous to check crashed container logs.
Execute commands inside running containers
Debug running pods by executing commands directly inside containers with kubectl exec. Access interactive shells using -it flags, or run one-off commands to inspect files, check processes, or test network connectivity without stopping your applications.
Describe resources for debugging issues
The kubectl describe command delivers comprehensive resource information, including events, conditions, and configuration details. This kubectl troubleshooting tool reveals why pods fail to start, services can’t route traffic, or deployments get stuck.
Port forwarding for local development access
Connect to services running in your cluster using kubectl port-forward. This kubernetes resource monitoring technique lets you access databases, APIs, or web interfaces locally without exposing them publicly, perfect for development and debugging workflows.
Configuration and Secret Management Commands

Create and Update ConfigMaps for Application Settings
ConfigMaps store non-sensitive configuration data that your applications need to run properly. Use kubectl create configmap my-config --from-file=config.properties to create ConfigMaps from files, or kubectl create configmap app-settings --from-literal=database_url=mysql://localhost:3306 for key-value pairs. You can update existing ConfigMaps with kubectl patch configmap my-config --patch '{"data":{"new-key":"new-value"}}'.
Manage Sensitive Data with Secrets
Secrets handle sensitive information like passwords, API keys, and certificates securely within your Kubernetes cluster. Create secrets using kubectl create secret generic db-secret --from-literal=username=admin --from-literal=password=secretpass. View secret data with kubectl get secret db-secret -o yaml, though values appear base64 encoded for security. Delete secrets when no longer needed using kubectl delete secret db-secret.
Apply Configuration Changes from YAML Files
The kubectl apply command manages kubectl configuration changes from YAML manifests efficiently. Run kubectl apply -f config.yaml to create or update resources defined in your configuration files. This command works great for both ConfigMaps and Secrets defined declaratively. Use kubectl apply -f . to apply all YAML files in your current directory, making bulk configuration updates simple and repeatable across different environments.
Scaling and Deployment Management Commands

Scale applications up or down dynamically
Managing application scale in Kubernetes becomes simple with kubectl deployment commands. The kubectl scale command lets you adjust replica counts instantly – just specify the deployment name and desired replicas like kubectl scale deployment nginx --replicas=5. For automatic scaling based on CPU usage, use kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80 to handle traffic spikes without manual intervention.
Update deployments with rolling updates
Rolling updates keep your applications running while deploying new versions. Use kubectl set image deployment/nginx nginx=nginx:1.21 to update container images seamlessly. The kubectl apply -f deployment.yaml command also triggers rolling updates when you modify deployment configurations. You can control update speed with kubectl patch deployment nginx -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":2,"maxUnavailable":1}}}}' to customize how many pods get replaced simultaneously.
Rollback to previous deployment versions
Deployment rollbacks save you when updates go wrong. Check your deployment history with kubectl rollout history deployment/nginx to see available versions. Roll back to the previous version using kubectl rollout undo deployment/nginx, or target a specific revision with kubectl rollout undo deployment/nginx --to-revision=2. Each rollback creates a new revision, so you can always move forward or backward through your deployment timeline.
Monitor rollout status and progress
Track deployment progress with kubernetes troubleshooting commands like kubectl rollout status deployment/nginx to watch updates in real-time. The kubectl get pods -w command shows pod changes as they happen during rollouts. Use kubectl describe deployment nginx to check detailed rollout conditions and events. When rollouts get stuck, kubectl rollout restart deployment/nginx forces a fresh rollout cycle to get things moving again.

Getting comfortable with kubectl commands opens up a whole new world of container management possibilities. From checking cluster health and managing pods to handling secrets and scaling applications, these commands form the backbone of your daily Kubernetes operations. Master the basics like kubectl get, kubectl describe, and kubectl logs, and you’ll find yourself troubleshooting issues faster and managing deployments with confidence.
Start practicing these commands in a safe environment – maybe spin up a local cluster or use a playground setup. The more you use kubectl, the more natural these operations become. Soon you’ll be chaining commands together and automating routine tasks like a pro. Your future self will thank you for taking the time to learn these fundamentals properly.
The post Kubernetes Basics: Common kubectl Commands Explained first appeared on Business Compass LLC.
from Business Compass LLC https://ift.tt/LP1A640
via IFTTT
Comments
Post a Comment