Introduction
In the dynamic world of container orchestration, mastering Kubernetes is crucial for efficient management and deployment. This comprehensive guide will delve into essential Kubectl Cheat Sheet commands, cheats, and advanced techniques to empower you in navigating the Kubernetes landscape.
Kubectl Cheat Sheet Basics:
1. Get Cluster Info
kubectl cluster-inf
Understanding your cluster’s information is the first step in effective Kubernetes management.
2. Display Nodes
kubectl get nodes
Discover and monitor the nodes in your Kubernetes cluster effortlessly.
3. Get All Pods
kubectl get pods --all-namespaces
The “kubectl get pods –all-namespaces” command provides a comprehensive view of all pods across namespaces. It displays detailed information, including pod names, statuses, and other relevant details, offering a global overview of pod instances within the entire Kubernetes cluster.
Kubectl Cheat Sheet for Pods: Mastering Pod Operations
4. List Pods in a Namespace
kubectl get pods -n <namespace>
The “kubectl get pods -n <namespace>” command retrieves a list of pods within the specified namespace. This includes information such as pod names, status, restarts, and other relevant details, offering an overview of the pod instances in the designated namespace.
5. Describe a Pod
kubectl describe pod <pod-name> -n <namespace>
The “kubectl describe pod <pod-name> -n <namespace>” command provides detailed information about a specific pod within the specified namespace. This includes data such as pod status, events, conditions, and container details, aiding in troubleshooting and understanding pod behavior.
6. Delete a Pod
kubectl delete pod <pod-name> -n <namespace>
The “kubectl delete pod <pod-name> -n <namespace>” command removes a specific pod from the specified namespace, triggering its termination. This action can be useful for updating or troubleshooting, ensuring the deletion and subsequent recreation of the pod with updated configurations.
Kubectl Cheat Sheet for Deployments: Streamlining Deployment Management
7. List Deployments
kubectl get deployments -n <namespace>
The “kubectl get deployments -n <namespace>” command displays a list of deployments within the specified namespace, presenting essential details like deployment names, the desired number of replicas, the current replica count, and deployment status, facilitating efficient monitoring and management of deployments.
8. Scale Deployment
kubectl scale deployment <deployment-name> --replicas=<desired-replicas> -n <namespace>
This command adjusts the number of replicas for a specified deployment in the given namespace, allowing dynamic scaling to meet workload demands, ensuring optimal resource utilization and application performance.
Scale your deployments seamlessly to meet changing demand and optimize resource utilization.
9. Update Deployment Image
kubectl set image deployment/<deployment-name> <container-name>=<new-image> -n <namespace>
The “kubectl set image deployment/<deployment-name> <container-name>=<new-image> -n <namespace>” command updates the container image for a specific container within a Kubernetes deployment in the specified namespace, facilitating seamless rolling updates and maintaining deployment history for tracking changes.
Networking Kubectl Cheat Sheet : Enhancing Connectivity
10. Port Forwarding
kubectl port-forward pod/<pod-name> <local-port>:<pod-port> -n <namespace>
The “kubectl port-forward pod/<pod-name> <local-port>:<pod-port> -n <namespace>” command establishes a local port-forwarding tunnel, enabling direct access to a pod within the specified namespace on the local machine via the designated local port.
11. Create a Service
kubectl expose deployment <deployment-name> --type=LoadBalancer --port=<external-port> -n <namespace>
This kubectl cheat sheet command exposes a Kubernetes deployment as a LoadBalancer service in the specified namespace, providing external access to the application through the assigned external port.
12. Ingress Controller
# Install Ingress Controller
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml -n <namespace>
This kubectl cheat sheet command deploys the Ingress Nginx controller in the specified namespace, enabling advanced routing and managing external access to services in a Kubernetes cluster.
Enhance network routing and external access with the installation of an Ingress Controller.
Kubectl Cheat Sheet for Packet Analysis:
13. Packet Capture
# Use tcpdump to capture packets
kubectl exec -it <pod-name> -n <namespace> -- tcpdump -i any -w /tmp/capture.pcap
The “kubectl exec -it <pod-name> -n <namespace> — tcpdump -i any -w /tmp/capture.pcap” command executes tcpdump within a specific pod in the given namespace, capturing network traffic on all interfaces and saving it to a file for subsequent analysis.
14. Analyze Packets
# Transfer pcap file to local and analyze with Wireshark
kubectl cp <namespace>/<pod-name>:/tmp/capture.pcap ./capture.pcap
The “kubectl cp <namespace>/<pod-name>:/tmp/capture.pcap ./capture.pcap” command copies a packet capture file, typically obtained using tcpdump within a pod, from a specified namespace to the local machine for analysis using tools like Wireshark.
Advanced Kubernetes Kubectl Cheat Sheet : Elevating Your Kubernetes
15. Resource Metrics
kubectl top nodeskubectl top pods -n <namespace>
The “kubectl top nodes” command provides real-time resource usage metrics for nodes in the cluster, displaying CPU and memory usage. Meanwhile, “kubectl top pods -n <namespace>” does the same but for pods within a specific namespace, aiding in performance analysis and optimization.
16. Rollback Deployment
kubectl rollout undo deployment/<deployment-name> -n <namespace>
The "kubectl rollout undo" command for deployments in Kubernetes allows reverting to a previous revision of the specified deployment (<deployment-name>) within the specified namespace (-n <namespace>). This feature is crucial for efficiently handling rollbacks and ensuring application stability during updates
Rollback deployments effortlessly in case of issues, ensuring system stability.
17. CronJob kubectl cheat sheet
kubectl get cronjobs -n <namespace>kubectl delete cronjob <cronjob-name> -n <namespace>
The “kubectl get cronjobs” command displays a list of cron jobs in the specified namespace, providing insights into scheduled tasks. The subsequent “kubectl delete cronjob” command removes a specific cron job (<cronjob-name>) from the namespace, allowing efficient management of recurring automated jobs in a Kubernetes environment.
18. Secret Management
kubectl create secret generic <secret-name> --from-literal=<key>=<value> -n <namespace>
The “kubectl create secret generic” command generates a generic secret named <secret-name> in the specified namespace. It populates the secret with sensitive data, such as passwords or API keys, derived from the provided key-value pair (<key>=<value>). This enhances security by securely managing and distributing confidential information in a Kubernetes environment.
Custom Kubectl Cheat Sheet : Tailoring Kubernetes for Your Needs
19. Custom Resource Definitions (CRDs)
kubectl get crds
kubectl get <custom-resource> -n <namespace>
The “kubectl get crds” command retrieves a list of Custom Resource Definitions (CRDs) in the cluster. Additionally, “kubectl get <custom-resource>” fetches instances of a specific custom resource within the specified namespace. These commands aid in managing and querying custom resources in a Kubernetes environment.
20. Apply YAML Configuration
kubectl apply -f <config-file>.yaml -n <namespace>
The “kubectl apply” command facilitates the application of Kubernetes configuration specified in a YAML file. When applied in the designated namespace, it deploys or updates resources defined in the YAML configuration file within the Kubernetes cluster.
21. Helm Chart Install
helm install <release-name> <chart-name> -n <namespace>
The “helm install” command deploys a Helm chart in the specified Kubernetes namespace. It initiates the installation of the specified Helm chart, creating instances of the application with the given release name within the designated namespace.
Kubectl Cheat Sheet: Packet Analysis Advanced Network Techniques
22. Analyze Network Policies
kubectl get networkpolicies -n <namespace>
The “kubectl get networkpolicies” command, within a specified namespace, retrieves information about existing Network Policies. It lists the policies configured in the Kubernetes cluster, offering insights into network segmentation and access control for pods within the designated namespace.
23. Port Scanning
kubectl exec -it <pod-name> -n <namespace> -- sh -c "nc -zv <target-host> <target-port>"
The “kubectl exec” command launches a shell in a specified pod and namespace, executing the “nc -zv” command to check the connectivity to a target host on a specific port. This facilitates network troubleshooting by verifying reachability and connectivity.
24. Capture Specific Interface
kubectl exec -it <pod-name> -n <namespace> -- tcpdump -i eth0 -w /tmp/capture.pcap
The “kubectl exec” command runs the tcpdump tool inside a specified pod and namespace, capturing network traffic on interface eth0. Captured data is written to /tmp/capture.pcap, facilitating in-depth packet analysis for troubleshooting and network diagnostics.
Dynamic Kubectl Cheat Sheet : Adapting to Changing Environments
25. Auto-Scaling
kubectl autoscale deployment <deployment-name> --min=<min-replicas> --max=<max-replicas> -n <namespace>
The “kubectl autoscale deployment” command dynamically adjusts the number of replicas in a deployment based on demand, ensuring optimal resource utilization. Parameters like min and max replicas define the scaling range within the specified namespace.
26. Dynamic Config Reload
kubectl rollout restart deployment <deployment-name> -n <namespace>
This kubectl cheat sheet command initiates a rolling restart of a deployment in the specified namespace. It gracefully replaces existing pods with new ones, ensuring continuous availability and applying any changes made to the deployment.
In short, Reload configurations dynamically for seamless updates and improvements.
27. Dynamic Pod Affinity
kubectl label nodes <node-name> <label-key>=<label-value>
kubectl label pods <pod-name> <label-key>=<label-value> -n <namespace>
These kubectl commands enable the labeling of Kubernetes nodes and pods for better organization and management. “kubectl label nodes” assigns labels to a specific node, while “kubectl label pods” assigns labels to a pod within a specified namespace.
28. Debugging Techniques: Resolving Issues Like a Pro
Troubleshooting is an integral skill. Use kubectl to debug issues efficiently:
kubectl describe <resource-type> <resource-name> -n <namespace>
kubectl logs <pod-name> -n <namespace>
These kubectl cheat sheet commands aid in troubleshooting and debugging. "kubectl describe" provides detailed information about a specific resource in a namespace, while "kubectl logs" retrieves the logs from a specific pod within the specified namespace.
29. Advanced Service Discovery: Navigating Through Services
Explore and understand services in-depth with these commands:
kubectl get services -n <namespace>
kubectl describe service <service-name> -n <namespace>
These kubectl commands retrieve information about services within a specified namespace. "kubectl get services" lists available services, while "kubectl describe service" provides detailed information about a specific service, including its configuration and status.
30. Persistent Volume Management: Handling Data Storage
Effectively manage persistent volumes and claims with kubectl:
kubectl get pvkubectl get pvc -n <namespace>
These kubectl cheat sheet commands retrieve information about persistent volumes (PVs) and persistent volume claims (PVCs) within a specified namespace. They provide insights into the storage resources available and the corresponding claims made by applications.
31. Node Maintenance Commands: Keeping Nodes Healthy
Ensure the health of your nodes with these essential commands:
kubectl drain <node-name> --ignore-daemonsets
kubectl uncordon <node-name>
These kubectl cheat sheet commands assist in node maintenance. "kubectl drain" safely evacuates pods from a node, ignoring daemon sets, preparing it for maintenance. "kubectl uncordon" allows the node to resume scheduling pods after maintenance is complete.
32. Helm Chart Management: Taking Control with Helm
Master Helm chart operations for seamless application management:
helm list -n <namespace>
helm upgrade <release-name> <chart-name> -n <namespace>
These Helm commands manage Helm releases within a specified namespace. The first lists all installed releases in the namespace, while the second upgrades a Helm release with a new chart or configuration.
33. Namespace Exploration: Organizing Your Cluster
Efficiently manage namespaces using kubectl:
kubectl get namespaceskubectl create namespace <new-namespace>
These kubectl cheat sheet commands list existing namespaces in a Kubernetes cluster and create a new namespace named "<new-namespace>," facilitating organization and isolation of resources within the Kubernetes environment.
34. Custom Metrics Extraction: Tailoring Monitoring
Extract custom metrics for a detailed monitoring approach:
kubectl get --raw=/apis/custom.metrics.k8s.io/v1beta1
kubectl get –raw=/apis/custom.metrics.k8s.io/v1beta1/namespaces/<namespace>/<metric-name>
These kubectl cheat sheet commands retrieve custom metrics information from the Kubernetes API. The first fetches custom metrics at the cluster level, while the second targets a specific namespace and metric name for detailed metric data.
35. Resource Cleanup Commands: Tidying Up Resources
Safely clean up unused resources with these commands:
kubectl delete <resource-type> <resource-name> -n <namespace>
kubectl delete all --all -n <namespace>
These kubectl cheat sheet commands delete specified resources of a given type and name within a namespace, providing a controlled removal. The second command deletes all resources across all types in the specified namespace for cleanup.
36. Scheduling Configurations: Optimizing Resource Allocation
Fine-tune scheduling configurations to optimize resource allocation:
kubectl describe node <node-name>kubectl describe pod <pod-name> -n <namespace>
These kubectl cheat sheet commands provide detailed information about a Kubernetes node and a pod within a specified namespace, offering insights into their configurations, status, and associated attributes for troubleshooting and analysis.
37. Helm Hooks: Executing Actions on Events
Leverage Helm hooks for executing actions during releases:#
# Example hook in Helm chart
——————————————————————————————-
hooks:
- id: my-hook
events:
- pre-install
command: ["echo", "Executing pre-install hook"]
———————————————————————————————
This YAML configuration defines a Helm hook named "my-hook" triggering a pre-install event, executing an "echo" command.
38. ConfigMap Tricks: Managing Configurations
Utilize ConfigMaps effectively for managing configuration data:
kubectl create configmap <configmap-name> --from-file=<path-to-file> -n <namespace>
kubectl get configmap <configmap-name> -n <namespace>
These kubectl cheat sheet commands are used to create a ConfigMap in a specified namespace by sourcing its data from a file or directory. The second command retrieves information about the created ConfigMap within the specified namespace. ConfigMaps are used to store configuration data that can be consumed by pods running within a Kubernetes cluster.
39. kubectl Plugins: Extending Functionality
Explore additional functionalities through kubectl plugins:
kubectl krew install <plugin-name>
kubectl <plugin-name> <arguments>
These kubectl cheat sheet commands are used to install and execute a kubectl plugin using Krew. Krew simplifies the management of kubectl plugins, allowing users to extend the functionality of kubectl with additional commands and features provided by plugins. Once installed, users can use the specified <plugin-name> and pass relevant <arguments> to interact with the plugin's functionality.
40. Workload Analysis: Understanding Resource Usage
Analyze workload and resource usage for better optimization:
kubectl top pods
Displays real-time resource usage metrics for pods in the default namespace.
Shows information such as CPU and memory usage for each pod.
Useful for assessing the performance of individual pods and identifying potential resource bottlenecks.
kubectl top nodes
Displays real-time resource usage metrics for nodes in the cluster.
Shows information such as CPU and memory usage for each node.
Useful for assessing the overall resource utilization of the cluster and identifying nodes that may need scaling or optimization.
41. Dynamic Cluster Scaling: Adapting to Demand Changes
Ensure your cluster dynamically scales to meet varying workloads:
kubectl cluster autoscaler -n <namespace> --max=<max-nodes> --min=<min-nodes> --nodes=<nodes-pool>
This kubectl cheat sheet command is used to configure the Kubernetes Cluster Autoscaler, which automatically adjusts the number of nodes in a node pool based on resource demands within a specified range defined by --min and --max parameters. The --nodes parameter sets the initial size of the node pool. Autoscaling helps optimize resource utilization and accommodate varying workloads in a Kubernetes cluster.
42. Efficient Pod Resource Requests: Optimizing Performance
Fine-tune pod resource requests to ensure optimal performance:
kubectl set resources deployment/<deployment-name> -n <namespace> --requests=<resource-requests>
This kubectl cheat sheet command allows you to adjust the resource requests (CPU and memory) for the containers within a deployment. Resource requests are used by the Kubernetes scheduler to allocate resources on nodes effectively. Adjusting resource requests can impact how resources are allocated and scheduled within the cluster, influencing the performance and stability of the deployed application.
43. Rolling Updates: Ensuring Smooth Application Transitions
Execute rolling updates for applications with minimal downtime:
kubectl set image deployment/<deployment-name> <container-name>=<new-image> --record -n <namespace>
This kubectl cheat sheet command updates the container image for a specific container within a Kubernetes deployment, and the change can be recorded in the deployment’s history for tracking purposes. This is useful for rolling updates to applications running in a Kubernetes cluster.
44. Helm Values Override: Customizing Helm Charts
Override Helm chart values for tailored deployments:
helm install <release-name> <chart-name> -n <namespace> --set <key1>=<value1>,<key2>=<value2>
This Helm command installs a Helm chart in a Kubernetes cluster, configuring it with specific values and deploying it within the specified namespace. The release name provides a unique identifier for the installed instance of the chart.
45. Job and CronJob Execution: Automated Task Management
Execute one-time jobs or scheduled tasks effortlessly:
kubectl create job <job-name> --image=<job-image> -n <namespace>
kubectl create cronjob <cronjob-name> --schedule=<schedule> --image=<cronjob-image> -n <namespace>
Automate tasks with job and cronjob functionalities.
46. Namespace Deletion: Efficient Cleanup
Delete a namespace and its resources securely:
kubectl delete namespace <namespace>
This kubectl cheat sheet command is a powerful operation and should be used with caution, as it permanently removes all resources and configurations associated with the specified namespace. It is typically used when you want to clean up and remove an entire logical grouping of resources within a Kubernetes cluster.
47. Kubernetes Dashboard Access: Visualize Cluster Data
Gain insights into your cluster with the Kubernetes dashboard:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.3.1/aio/deploy/recommended.yaml -n <namespace>
kubectl proxy
These kubectl cheat sheet commands deploy the Kubernetes Dashboard and start a proxy server, enabling you to access the Dashboard locally. You can then open the Dashboard in a web browser to interact with and monitor the resources in your Kubernetes cluster.
48. Pod Security Policies: Enhancing Security Measures
Implement Pod Security Policies for robust security:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/website/main/content/en/examples/policy/podsecuritypolicy/rbac.yaml -n <namespace>
kubectl apply -f https://raw.githubusercontent.com/kubernetes/website/main/content/en/examples/policy/podsecuritypolicy/psp-rbac.yaml -n <namespace>
These kubectl cheat sheet commands set up RBAC configurations for Pod Security Policies in a Kubernetes cluster, ensuring that only authorized entities have the necessary permissions to manage and enforce security policies for pods within the specified namespace.
49. Horizontal Pod Autoscaling: Dynamic Pod Adjustment
Analyze workload and resource usage for better optimization:
kubectl autoscale deployment <deployment-name> --cpu-percent=<cpu-percent> --min=<min-pods> --max=<max-pods> -n <namespace>
This kubectl cheat sheet command automates the adjustment of the number of pods in a deployment based on CPU usage, optimizing resource utilization and ensuring that the application scales dynamically in response to changing workloads.
50. Advanced Ingress Routing: Fine-Tuning Routing Rules
Enhance Ingress functionality with advanced routing rules:
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/cloud/deploy.yaml -n <namespace>
kubectl apply -f <custom-ingress-rules>.yaml -n <namespace>
The “kubectl apply” commands deploy the Ingress Nginx controller in a specified namespace, enhancing external access to Kubernetes services. The second command applies custom Ingress rules defined in a YAML file, allowing fine-tuning of routing configurations in the designated namespace.
