# kubectl Quick Reference Guide ## 🚀 **Essential Commands for Junior Engineers** ### **Basic Resource Management** ```bash # Get resources kubectl get pods kubectl get deployments kubectl get services kubectl get namespaces kubectl get configmaps kubectl get secrets kubectl get pvc kubectl get ingress # Get all resources in namespace kubectl get all -n # Get resources with labels kubectl get pods -l app=web-app kubectl get pods -l environment=production # Get resources in wide format kubectl get pods -o wide kubectl get nodes -o wide ``` ### **Resource Creation** ```bash # Create from YAML file kubectl apply -f # Create from directory kubectl apply -f / # Create from URL kubectl apply -f https://raw.githubusercontent.com/... # Create resources directly kubectl create namespace my-app kubectl create deployment nginx --image=nginx:latest kubectl create service clusterip nginx --tcp=80:80 kubectl create configmap app-config --from-literal=DB_HOST=postgres kubectl create secret generic db-secret --from-literal=DB_PASSWORD=secret123 ``` ### **Resource Inspection** ```bash # Describe resources kubectl describe pod kubectl describe deployment kubectl describe service kubectl describe namespace # Get resource YAML kubectl get pod -o yaml kubectl get deployment -o yaml # Get resource in specific format kubectl get pod -o json kubectl get pod -o jsonpath='{.spec.containers[0].image}' ``` ### **Logs and Debugging** ```bash # View logs kubectl logs kubectl logs -f # Follow logs kubectl logs --previous # Previous container kubectl logs --tail=100 # Last 100 lines # Execute commands in pods kubectl exec -it -- /bin/bash kubectl exec -- ls /app kubectl exec -- cat /etc/passwd # Port forwarding kubectl port-forward 8080:80 kubectl port-forward service/ 8080:80 kubectl port-forward deployment/ 8080:80 ``` ### **Scaling and Updates** ```bash # Scale deployments kubectl scale deployment --replicas=5 kubectl scale deployment --replicas=0 # Scale to zero # Update deployments kubectl set image deployment/ = kubectl set image deployment/nginx nginx=nginx:1.21 # Rollout management kubectl rollout status deployment/ kubectl rollout history deployment/ kubectl rollout undo deployment/ kubectl rollout pause deployment/ kubectl rollout resume deployment/ ``` ### **Resource Deletion** ```bash # Delete resources kubectl delete pod kubectl delete deployment kubectl delete service kubectl delete namespace # Delete from YAML file kubectl delete -f # Delete all resources in namespace kubectl delete all --all -n # Force delete (use with caution) kubectl delete pod --force --grace-period=0 ``` ### **Context and Namespace Management** ```bash # View current context kubectl config current-context # List contexts kubectl config get-contexts # Switch context kubectl config use-context # Set default namespace kubectl config set-context --current --namespace= # View cluster info kubectl cluster-info kubectl cluster-info dump ``` ### **Resource Monitoring** ```bash # Check resource usage kubectl top pods kubectl top nodes kubectl top pods --containers # Check events kubectl get events kubectl get events -n kubectl get events --sort-by='.lastTimestamp' # Check resource quotas kubectl get resourcequota kubectl describe resourcequota ``` ### **Troubleshooting Commands** ```bash # Check node status kubectl get nodes kubectl describe node # Check service endpoints kubectl get endpoints kubectl describe endpoints # Check persistent volumes kubectl get pv kubectl get pvc kubectl describe pv # Check ingress kubectl get ingress kubectl describe ingress # Check jobs and cronjobs kubectl get jobs kubectl get cronjobs kubectl describe job kubectl describe cronjob ``` ### **Useful Aliases** ```bash # Add to your .bashrc or .zshrc alias k='kubectl' alias kg='kubectl get' alias kd='kubectl describe' alias kl='kubectl logs' alias ke='kubectl exec -it' alias kp='kubectl port-forward' alias ka='kubectl apply -f' alias kdel='kubectl delete' alias kctx='kubectl config use-context' alias kns='kubectl config set-context --current --namespace' ``` ### **Common Patterns** ```bash # Get all pods with their IPs kubectl get pods -o wide # Get all services with their endpoints kubectl get services -o wide # Get all resources in a namespace kubectl get all -n # Get resources by label kubectl get pods -l app=web-app,environment=production # Get resources sorted by creation time kubectl get pods --sort-by=.metadata.creationTimestamp # Get resources in custom columns kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,AGE:.metadata.creationTimestamp ``` ### **Advanced Commands** ```bash # Patch resources kubectl patch deployment -p '{"spec":{"replicas":5}}' # Edit resources kubectl edit deployment kubectl edit configmap # Copy files kubectl cp :/path/in/pod kubectl cp :/path/in/pod # Run temporary pods kubectl run test-pod --image=busybox --rm -it --restart=Never -- wget -O- : # Check API resources kubectl api-resources kubectl explain ``` ### **Context-Specific Commands** ```bash # For debugging network issues kubectl run test-pod --image=busybox --rm -it --restart=Never -- wget -O- : # For checking storage kubectl run test-pod --image=busybox --rm -it --restart=Never -- ls /data # For testing DNS kubectl run test-pod --image=busybox --rm -it --restart=Never -- nslookup # For checking secrets kubectl run test-pod --rm -it --restart=Never --image=busybox -- env | grep DB_ ``` ## ⚠️ **Bad Practices to Avoid** ### **❌ DON'T DO THIS** ```bash # ❌ NEVER use kubectl run for production applications kubectl run my-app --image=my-app:latest --port=8080 # ❌ NEVER create standalone Pods for services kubectl run database --image=postgres:13 --port=5432 # ❌ NEVER use imperative commands for production kubectl run nginx --image=nginx:latest # ❌ NEVER delete Pods directly (they'll be recreated by Deployment) kubectl delete pod # ❌ NEVER use --force without understanding the consequences kubectl delete pod --force --grace-period=0 ``` ### **✅ DO THIS INSTEAD** ```bash # ✅ Use Deployments for applications kubectl create deployment my-app --image=my-app:latest # ✅ Use Helm charts for complex applications helm install my-app ./my-app-chart --namespace my-app # ✅ Use kubectl apply for declarative deployments kubectl apply -f deployment.yaml # ✅ Use StatefulSets for databases kubectl apply -f statefulset.yaml # ✅ Delete Deployments, not Pods kubectl delete deployment # ✅ Use proper resource management kubectl scale deployment --replicas=0 ``` ### **🔧 When `kubectl run` is Acceptable** ```bash # ✅ OK: One-time debugging pods kubectl run debug-pod --image=busybox --rm -it --restart=Never -- nslookup my-service # ✅ OK: Temporary testing kubectl run test-pod --image=nginx --rm -it --restart=Never -- curl http://my-service:80 # ✅ OK: Quick experiments (development only) kubectl run temp-pod --image=nginx --port=80 # ✅ OK: Troubleshooting network issues kubectl run test-pod --image=busybox --rm -it --restart=Never -- wget -O- my-service:80 ``` ## 🏭 **Your Codebase Best Practices** ### **Your Actual Commands** ```bash # 🏭 REAL COMMANDS FROM YOUR CODEBASE # From freeleaps-devops-reconciler/scripts/deploy.sh # Helm deployment (primary method) helm install/upgrade "$RELEASE_NAME" . \ --namespace "$NAMESPACE" \ --create-namespace \ -f "$VALUES_FILE" \ --set "image.tag=$IMAGE_TAG" # kubectl apply (secondary method) kubectl apply -f / # Status checking kubectl get pods -n "$NAMESPACE" -l "app.kubernetes.io/name=freeleaps-devops-reconciler" kubectl logs -n "$NAMESPACE" deployment/"$RELEASE_NAME" ``` ### **Best Practices** 1. **Always use namespaces** to organize resources 2. **Use labels** for better resource management 3. **Set resource limits** on all containers 4. **Use health checks** for reliability 5. **Use ConfigMaps and Secrets** for configuration 6. **Test changes** in a staging environment first 7. **Keep kubectl updated** to match your cluster version 8. **Use Deployments, not standalone Pods** 9. **Use Helm charts for complex applications** 10. **Use declarative YAML files** ### **Common Mistakes to Avoid** ```bash # ❌ Don't do this kubectl run nginx --image=nginx # Creates a pod, not a deployment # ✅ Do this instead kubectl create deployment nginx --image=nginx # ❌ Don't do this kubectl delete pod # Pod will be recreated by deployment # ✅ Do this instead kubectl delete deployment # ❌ Don't do this kubectl exec -- rm -rf / # Dangerous command # ✅ Do this instead kubectl exec -- ls / # Safe inspection command ```