00-A

Quick Reference

Essential kubectl commands at a glance. The most frequently used operations for day-to-day cluster management.

Cluster & Context
kubectl cluster-infoCluster endpoint
kubectl config get-contextsList contexts
kubectl config use-context CTXSwitch context
kubectl config current-contextCurrent ctx
kubectl versionClient/server ver
Pods
kubectl get pods [-A] [-w]List pods
kubectl describe pod PODPod details
kubectl logs POD [-f] [-c]View logs
kubectl exec -it POD -- shShell into pod
kubectl port-forward POD 8080:80Forward port
kubectl delete pod PODDelete pod
Deployments
kubectl create deploy D --image=ICreate
kubectl scale deploy D --replicas=NScale
kubectl set image deploy/D C=IUpdate image
kubectl rollout status deploy/DRollout status
kubectl rollout undo deploy/DRollback
kubectl rollout restart deploy/DRolling restart
Services & Networking
kubectl expose deploy D --port=80Create svc
kubectl get svc [-A]List services
kubectl get endpoints SVCEndpoints
kubectl get ingressList ingress
kubectl get netpolNetwork policies
Resources & Config
kubectl apply -f FILEApply manifest
kubectl delete -f FILEDelete from file
kubectl diff -f FILEDiff changes
kubectl edit TYPE NAMEEdit resource
kubectl get cm / secretsConfigMaps/Secrets
Debugging
kubectl describe TYPE NAMEResource details
kubectl get events --sort-by=.lastTimestampEvents
kubectl top pod / nodeResource usage
kubectl debug POD -it --image=busyboxDebug pod
kubectl api-resourcesAll resources
kubectl explain TYPEResource docs
01-A

Cluster Info & Config

Commands for inspecting cluster state, managing kubeconfig contexts, and switching between clusters.

Cluster Information

# Display cluster endpoint and DNS kubectl cluster-info # Full cluster info dump (for debugging) kubectl cluster-info dump # Client and server versions kubectl version # View the kubeconfig file kubectl config view

Context Management

# List all available contexts kubectl config get-contexts # Show current context kubectl config current-context # Switch to a different context kubectl config use-context <context-name> # Set namespace for a context kubectl config set-context <context-name> --namespace=<namespace> # Rename a context kubectl config rename-context <old-name> <new-name> # Delete a context kubectl config delete-context <context-name>

Kubeconfig Structure

apiVersion: v1 kind: Config clusters: - name: my-cluster cluster: server: https://cluster-api-endpoint certificate-authority-data: <base64-cert> contexts: - name: my-context context: cluster: my-cluster user: my-user namespace: default current-context: my-context users: - name: my-user user: token: <auth-token>
02-A

Pods

The smallest deployable unit in Kubernetes. Commands for creating, inspecting, debugging, and managing pods.

Pod Lifecycle States
Pending Running Succeeded | Failed | Unknown | CrashLoopBackOff

Listing & Inspecting Pods

# List pods in current namespace kubectl get pods # All namespaces, wide output, watch mode kubectl get pods -A kubectl get pods -o wide kubectl get pods --watch # Sorted by restart count kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # Show labels kubectl get pods --show-labels # Describe a specific pod kubectl describe pod <pod-name> # Get YAML/JSON output kubectl get pod <pod-name> -o yaml kubectl get pod <pod-name> -o json

Pod Logs

# Basic log viewing kubectl logs <pod-name> # Follow logs in real-time kubectl logs <pod-name> -f # Specific container in multi-container pod kubectl logs <pod-name> -c <container> # Previous container instance (after restart) kubectl logs <pod-name> --previous # Time-based filtering kubectl logs <pod-name> --since=1h kubectl logs <pod-name> --since-time=2026-02-09T10:00:00Z # Last N lines with timestamps kubectl logs <pod-name> --tail=100 --timestamps # All containers in a pod kubectl logs <pod-name> --all-containers=true

Exec, Port-Forward & Copy

# Interactive shell kubectl exec -it <pod-name> -- /bin/bash kubectl exec -it <pod-name> -- /bin/sh # Run a command kubectl exec <pod-name> -- ls /app # Exec into specific container kubectl exec -it <pod-name> -c <container> -- sh # Port forwarding kubectl port-forward <pod-name> 8080:80 kubectl port-forward --address 0.0.0.0 <pod-name> 8080:80 kubectl port-forward service/<svc-name> 8080:80 # Copy files to/from pod kubectl cp /local/path <pod-name>:/container/path kubectl cp <pod-name>:/container/path /local/path

Creating & Deleting Pods

# Run a pod kubectl run <name> --image=<image> # With env vars, port, and labels kubectl run <name> --image=<image> --env="KEY=VALUE" --port=8080 -l app=myapp # Delete a pod / force delete kubectl delete pod <pod-name> kubectl delete pod <pod-name> --grace-period=0 --force # Resource usage (requires metrics-server) kubectl top pod kubectl top pod <pod-name> --containers
03-A

Deployments

Declarative updates for Pods and ReplicaSets. Create, scale, update, and rollback application deployments.

Create & View Deployments

# Create a deployment kubectl create deployment <name> --image=<image> # With replicas kubectl create deployment <name> --image=<image> --replicas=3 # Generate YAML without creating (dry-run) kubectl create deployment <name> --image=<image> --dry-run=client -o yaml # From a YAML file kubectl apply -f deployment.yaml # List / describe deployments kubectl get deployments kubectl get deploy -A kubectl describe deployment <name>

Scaling

# Manual scaling kubectl scale deployment <name> --replicas=5 # Autoscale based on CPU kubectl autoscale deployment <name> --min=2 --max=10 --cpu-percent=80

Rollouts & Updates

# Update container image kubectl set image deployment/<name> <container>=<new-image> # Check rollout status kubectl rollout status deployment/<name> # View rollout history kubectl rollout history deployment/<name> kubectl rollout history deployment/<name> --revision=2 # Rollback to previous / specific revision kubectl rollout undo deployment/<name> kubectl rollout undo deployment/<name> --to-revision=2 # Rolling restart (redeploy all pods) kubectl rollout restart deployment/<name> # Pause / resume rollout kubectl rollout pause deployment/<name> kubectl rollout resume deployment/<name>

Edit & Delete

kubectl edit deployment <name> kubectl delete deployment <name>
04-A

Services

Networking abstractions that expose pods as a network service. Four types define how traffic reaches your application.

TypeScopeUse Case
ClusterIPInternal only (default)Inter-service communication within cluster
NodePortExternal via node IP:portDevelopment, direct node access
LoadBalancerExternal cloud LBProduction traffic from internet
ExternalNameDNS CNAME aliasMapping to external services

Creating Services

# Expose a deployment (ClusterIP default) kubectl expose deployment <name> --port=80 --target-port=8080 # NodePort kubectl expose deployment <name> --port=80 --type=NodePort # LoadBalancer kubectl expose deployment <name> --port=80 --type=LoadBalancer # Expose a pod directly kubectl expose pod <pod-name> --port=80 --name=<svc-name>

Viewing & Deleting Services

kubectl get services kubectl get svc -A kubectl describe service <name> kubectl get endpoints <name> kubectl get svc <name> -o yaml kubectl delete service <name>
05-A

ConfigMaps & Secrets

Decouple configuration and sensitive data from container images. ConfigMaps for plain config, Secrets for sensitive values.

ConfigMaps

# From literal values kubectl create configmap <name> \ --from-literal=key1=val1 \ --from-literal=key2=val2 # From file / directory / env file kubectl create configmap <name> --from-file=<path> kubectl create configmap <name> --from-env-file=.env # View / edit / delete kubectl get cm kubectl describe configmap <name> kubectl get cm <name> -o yaml kubectl edit configmap <name> kubectl delete configmap <name>

Secrets

# Generic secret from literals kubectl create secret generic <name> \ --from-literal=user=admin \ --from-literal=pass=s3cret # From file / TLS / Docker registry kubectl create secret generic <name> --from-file=<path> kubectl create secret tls <name> --cert=c.pem --key=k.pem kubectl create secret docker-registry <name> \ --docker-server=<reg> --docker-username=<u> \ --docker-password=<p> # View / decode / delete kubectl get secrets kubectl get secret <name> -o yaml kubectl get secret <name> \ -o jsonpath='{.data.pass}' | base64 -d kubectl delete secret <name>
Security Note

Secrets are base64-encoded, not encrypted, by default. For production, enable encryption at rest in etcd or use external secret management (Vault, AWS Secrets Manager, etc.).

06-A

Namespaces

Virtual clusters for resource isolation. Organize by environment, team, or application.

# Create namespace kubectl create namespace <name> # List namespaces kubectl get namespaces kubectl get ns # Describe namespace kubectl describe namespace <name> # Work in a specific namespace kubectl get pods -n <namespace> kubectl get all -n <namespace> # Set default namespace for current context kubectl config set-context --current --namespace=<namespace> # View current namespace kubectl config view --minify | grep namespace: # Delete namespace (removes all resources within!) kubectl delete namespace <name>
Namespace Best Practices

Use namespaces for environment separation (dev/staging/prod). Apply ResourceQuotas and LimitRanges per namespace. Note that Secrets and ConfigMaps are namespace-scoped and cannot be shared across namespaces.

07-A

Resource Management

Core commands for applying, creating, editing, patching, and deleting Kubernetes resources declaratively and imperatively.

Apply, Create & Validate

# Apply (create or update) from file / directory / URL kubectl apply -f <file.yaml> kubectl apply -f <directory>/ kubectl apply -f https://example.com/resource.yaml # Apply multiple files kubectl apply -f a.yaml -f b.yaml # Create (fails if resource already exists) kubectl create -f <file.yaml> # Dry-run (client-side / server-side validation) kubectl apply -f <file.yaml> --dry-run=client kubectl apply -f <file.yaml> --dry-run=server # Show diff before applying kubectl diff -f <file.yaml>

Edit, Patch & Replace

# Edit resource interactively kubectl edit <type> <name> # Patch (partial update) kubectl patch <type> <name> -p '{"spec":{"replicas":3}}' # Replace (delete and recreate) kubectl replace -f <file.yaml> kubectl replace --force -f <file.yaml>

Delete Resources

# Delete by name / file / label / all kubectl delete <type> <name> kubectl delete -f <file.yaml> kubectl delete pods -l app=myapp kubectl delete <type> --all # With grace period / force kubectl delete pod <name> --grace-period=30 kubectl delete pod <name> --grace-period=0 --force
08-A

Inspection & Debugging

Tools for describing resources, viewing events, debugging containers, and monitoring resource consumption.

Describe & Events

# Describe any resource type kubectl describe <type> <name> kubectl describe pod <pod> kubectl describe node <node> # View cluster events kubectl get events kubectl get events --sort-by='.lastTimestamp' kubectl get events --watch # Filter events kubectl get events --field-selector type=Warning kubectl get events --field-selector involvedObject.name=<name>

Debug Containers

# Create debug container attached to running pod kubectl debug <pod> -it --image=busybox # Debug with specific target container kubectl debug <pod> -it --image=ubuntu --target=<container> # Debug a node (creates privileged pod) kubectl debug node/<node-name> -it --image=ubuntu # Create copy of pod for debugging kubectl debug <pod> -it --copy-to=<debug-pod> --image=<image>

Resource Metrics & API

# Node / pod resource usage kubectl top node kubectl top pod kubectl top pod -n <namespace> kubectl top pod --sort-by=cpu kubectl top pod --sort-by=memory kubectl top pod <pod> --containers # API discovery kubectl api-resources kubectl api-resources -o wide kubectl api-versions # Explain resource fields (built-in docs) kubectl explain pod kubectl explain pod.spec.containers kubectl explain pod.spec.containers --recursive # Health checks kubectl get --raw='/healthz' kubectl get --raw='/readyz'
Quick Debugging Workflow
1. kubectl get pods -- check pod status
2. kubectl describe pod <name> -- events & conditions
3. kubectl logs <name> -- application logs
4. kubectl logs <name> --previous -- logs from crashed container
5. kubectl exec -it <name> -- sh -- shell access
6. kubectl get events --sort-by=.lastTimestamp -- cluster events
7. kubectl top pod <name> -- resource consumption
09-A

Labels & Selectors

Key-value pairs for organizing and selecting resources. Labels enable powerful filtering; annotations store non-identifying metadata.

Managing Labels

# Add labels to a resource kubectl label pod <name> env=prod tier=frontend # Update existing label (requires --overwrite) kubectl label pod <name> env=staging --overwrite # Remove a label kubectl label pod <name> env- # Label all pods kubectl label pods --all version=v1 # Show labels kubectl get pods --show-labels

Filtering with Selectors

# Equality-based selectors kubectl get pods -l app=myapp kubectl get pods -l 'env=prod,tier=frontend' # Set-based selectors kubectl get pods -l 'env in (prod,staging)' kubectl get pods -l 'env notin (dev,test)' kubectl get pods -l 'release' # has label kubectl get pods -l '!release' # does not have label # Negation kubectl get pods -l 'app=myapp,env!=dev'

Field Selectors & Annotations

# Field selectors (filter by resource fields) kubectl get pods --field-selector status.phase=Running kubectl get pods --field-selector status.phase=Running,spec.nodeName=<node> kubectl get pods --field-selector status.phase!=Running # Combine label + field selectors kubectl get pods -l app=myapp --field-selector status.phase=Running # Annotations (non-identifying metadata) kubectl annotate pod <name> description="My pod" kubectl annotate pod <name> description="Updated" --overwrite kubectl annotate pod <name> description- # remove
10-A

Advanced Objects

Higher-order workloads and infrastructure resources: StatefulSets, DaemonSets, Jobs, CronJobs, Ingress, PV/PVC, NetworkPolicies, and HPA.

StatefulSets

kubectl apply -f statefulset.yaml kubectl get statefulsets # or: get sts kubectl describe statefulset <name> kubectl scale statefulset <name> --replicas=5 kubectl rollout restart statefulset/<name> kubectl rollout status statefulset/<name> kubectl delete statefulset <name> --cascade=orphan # keeps pods

DaemonSets

kubectl apply -f daemonset.yaml kubectl get daemonsets # or: get ds kubectl get ds -A kubectl describe daemonset <name> kubectl rollout restart daemonset/<name> kubectl delete daemonset <name>

Jobs & CronJobs

# Jobs kubectl create job <name> --image=<image> kubectl create job <name> --from=cronjob/<cj-name> kubectl get jobs kubectl logs job/<name> kubectl delete job <name> # CronJobs kubectl create cronjob <name> --image=<image> --schedule="*/5 * * * *" kubectl get cronjobs # or: get cj kubectl describe cronjob <name> # Suspend / resume kubectl patch cronjob <name> -p '{"spec":{"suspend":true}}' kubectl patch cronjob <name> -p '{"spec":{"suspend":false}}' # Manually trigger kubectl create job <job-name> --from=cronjob/<cj-name>
Networking & Storage

Ingress

kubectl apply -f ingress.yaml kubectl get ingress # or: get ing kubectl get ing -A kubectl describe ingress <name> kubectl edit ingress <name> kubectl delete ingress <name>
Ingress NGINX Retiring March 2026

Ingress NGINX will be retired in March 2026 with no further releases or security patches. Consider migrating to Gateway API. Check usage: kubectl get pods -A --selector app.kubernetes.io/name=ingress-nginx

PersistentVolumes & Claims

kubectl get persistentvolumes # or: get pv kubectl get persistentvolumeclaims # or: get pvc kubectl describe pv <name> kubectl describe pvc <name> kubectl apply -f pvc.yaml kubectl delete pvc <name>

NetworkPolicies

kubectl apply -f networkpolicy.yaml kubectl get networkpolicies # or: get netpol kubectl describe networkpolicy <name> kubectl delete networkpolicy <name> # Test connectivity kubectl exec -it <source-pod> -- curl <target-ip>
CNI Required

NetworkPolicies require a CNI plugin that supports them (Calico, Cilium, Weave Net). Policies are additive -- the union of all matching policies is applied.

Horizontal Pod Autoscaler

# Create HPA (requires metrics-server) kubectl autoscale deployment <name> --cpu-percent=50 --min=1 --max=10 # View / manage HPAs kubectl get hpa kubectl describe hpa <name> kubectl get hpa --watch kubectl edit hpa <name> kubectl delete hpa <name>
11-A

Output Formatting

Control how kubectl displays data. From wide tables to JSONPath queries to custom columns and Go templates.

Output Formats (-o)

FlagDescriptionExample
-o wideAdditional columns (node, IP)kubectl get pods -o wide
-o yamlFull YAML outputkubectl get pod X -o yaml
-o jsonFull JSON outputkubectl get pod X -o json
-o nameResource type/name onlykubectl get pods -o name
-o jsonpathJSONPath expressionkubectl get pods -o jsonpath='{..name}'
-o custom-columnsCustom table columnskubectl get pods -o custom-columns=N:.metadata.name
-o go-templateGo template formattingkubectl get pods -o go-template='...'
--no-headersOmit table headerskubectl get pods --no-headers

JSONPath Queries

# All pod names kubectl get pods -o jsonpath='{.items[*].metadata.name}' # Names with newlines kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' # Pod IP address kubectl get pod <name> -o jsonpath='{.status.podIP}' # First container image kubectl get pod <name> -o jsonpath='{.spec.containers[0].image}' # Multi-column tab-separated output kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}' # Filter running pods kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'

Custom Columns & Sorting

# Custom columns kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName,IP:.status.podIP # Container images column kubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[*].image # Sorting kubectl get pods --sort-by=.metadata.name kubectl get pods --sort-by=.metadata.creationTimestamp kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' kubectl get nodes --sort-by=.status.capacity.cpu

Go Templates

# Basic template kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' # With conditions kubectl get pods -o go-template='{{range .items}}{{if eq .status.phase "Running"}}{{.metadata.name}}{{"\n"}}{{end}}{{end}}'
12-A

Pro Tips

Aliases, shell completion, Kustomize, Helm basics, plugins, and essential one-liners for Kubernetes power users.

kubectl Aliases

# Add to ~/.bashrc or ~/.zshrc alias k='kubectl' alias kg='kubectl get' alias kd='kubectl describe' alias kdel='kubectl delete' alias kl='kubectl logs' alias kex='kubectl exec -it' alias ka='kubectl apply -f' alias kgp='kubectl get pods' alias kgd='kubectl get deployments' alias kgs='kubectl get services' alias kgn='kubectl get nodes' alias kgpa='kubectl get pods --all-namespaces' alias kns='kubectl config set-context --current --namespace' alias kctx='kubectl config current-context'

Shell Completion

# Bash echo 'source <(kubectl completion bash)' >> ~/.bashrc echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc # Zsh echo '[[ $commands[kubectl] ]] && source <(kubectl completion zsh)' >> ~/.zshrc # Fish kubectl completion fish | source

Dry Run & Explain

# Generate YAML without creating kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deploy.yaml # Server-side validation kubectl apply -f deploy.yaml --dry-run=server # Explore resource structure (built-in docs) kubectl explain pods kubectl explain pod.spec.containers kubectl explain deployment.spec.strategy
Tooling

Kustomize

# Apply kustomization kubectl apply -k <directory> # Preview kustomization output kubectl kustomize <directory> # Dry-run with kustomize kubectl apply -k <directory> --dry-run=client # Build to file kubectl kustomize <directory> > output.yaml
# kustomization.yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - deployment.yaml - service.yaml namespace: production namePrefix: prod- labels: - pairs: env: production

Helm Basics

# Repository management helm repo add <name> <url> helm repo update helm search repo <chart> # Install / upgrade / rollback helm install <release> <chart> helm install <release> <chart> -f values.yaml helm install <release> <chart> --set key=value helm upgrade <release> <chart> helm rollback <release> <revision> # Status / list / template / uninstall helm list helm status <release> helm template <release> <chart> helm uninstall <release>

kubectl Plugins (krew)

# Install krew plugin manager (see krew.sigs.k8s.io) kubectl krew install <plugin> kubectl krew list kubectl krew upgrade # Popular plugins kubectl krew install ctx # switch contexts kubectl krew install ns # switch namespaces kubectl krew install tree # resource hierarchy kubectl krew install neat # clean YAML output

Resource Quotas & Limits

# Resource quotas kubectl create quota <name> --hard=cpu=10,memory=20Gi,pods=10 kubectl get resourcequota kubectl describe quota # Limit ranges kubectl apply -f limitrange.yaml kubectl get limitranges kubectl describe limitrange <name> # Set resource limits on deployment kubectl set resources deployment <name> --limits=cpu=200m,memory=512Mi kubectl set env deployment/<name> ENV=production
Essential One-Liners
Useful One-Liners
# All pod IPs kubectl get pods -o jsonpath='{.items[*].status.podIP}' # All unique container images in use kubectl get pods -A -o jsonpath='{range .items[*]}{.spec.containers[*].image}{"\n"}{end}' | sort -u # Count pods by status kubectl get pods -A --no-headers | awk '{print $4}' | sort | uniq -c # Pods on a specific node kubectl get pods -A --field-selector spec.nodeName=<node> # Pod restart counts kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\n"}{end}' # Pods not running kubectl get pods -A --field-selector status.phase!=Running # Get multiple resource types at once kubectl get pods,services,deployments
Pro Tips Summary

Use kubectl explain instead of searching docs. Always test with --dry-run before applying changes. Use kubectl diff to preview what will change. Set up shell completion and aliases for speed. Use labels extensively for organization. Monitor events with kubectl get events -w. Combine -o jsonpath with jq for complex queries. Use Kustomize for environment-specific configs. Use kubectl debug for non-intrusive troubleshooting.