kubectl Cheat Sheet 2025 - Modern Kubernetes Commands

January 9, 2025

                                                                           

🚀 What’s New in This 2025 Update

Major Changes Since 2019

  • Kubernetes 1.33 - Latest stable version with enhanced features
  • Containerd Default - Docker runtime deprecated, containerd is standard
  • kubectl convert - Plugin for API version migrations
  • Enhanced Security - Checksum validation and GPG verification required
  • Cloud Integration - Native support for EKS, GKE, AKS workflows
  • GitOps Ready - Declarative management best practices

Key Improvements

  • ✅ Better Performance - Faster command execution and API responses
  • ✅ Enhanced Debugging - Improved error messages and troubleshooting
  • ✅ Modern Shell Support - Updated completion for latest shells
  • ✅ Security First - Mandatory verification for all downloads

Modern kubectl Setup and Shell Completion

Shell completion is essential for productive Kubernetes work. With macOS now defaulting to Zsh and modern Linux distributions offering various shells, here’s the updated setup.

Zsh Shell Completion (macOS Default)

# Add to ~/.zshrc
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
echo 'alias k=kubectl' >> ~/.zshrc
echo 'complete -o default -F __start_kubectl k' >> ~/.zshrc

# If using Oh My Zsh, enable the kubectl plugin
# In ~/.zshrc, add kubectl to plugins:
plugins=(... kubectl)

# Reload shell
source ~/.zshrc

Bash Shell Completion

# Install bash-completion first (if not installed)
# macOS: brew install bash-completion@2
# Linux: apt-get install bash-completion

# Add to ~/.bashrc
echo 'source <(kubectl completion bash)' >> ~/.bashrc
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc

# Reload shell
source ~/.bashrc

Modern Shell Features

# Enable completion for common aliases
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployment'
alias kaf='kubectl apply -f'
alias kdel='kubectl delete'
alias klog='kubectl logs'
alias kexec='kubectl exec -it'

Essential kubectl Commands 2025

Version Compatibility Check

# Check kubectl version (must be within 1 minor version of cluster)
kubectl version --client --short

# Check cluster version
kubectl version --short

# Detailed version info
kubectl version -o yaml

Resource Management with Field Selectors

# Get pods by status
kubectl get pods --field-selector=status.phase=Running

# Get nodes by condition
kubectl get nodes --field-selector=spec.unschedulable=false

# Combine with label selectors
kubectl get pods -l app=nginx --field-selector=status.phase=Running

Advanced Debugging Commands

Enhanced describe with Events Timeline

# Describe with sorted events
kubectl describe pod my-pod | grep -A 20 Events

# Get events for specific resource
kubectl get events --field-selector involvedObject.name=my-pod \
  --sort-by='.lastTimestamp'

# Watch events in real-time
kubectl get events -w --field-selector type=Warning

Container Runtime Debugging (Containerd)

# Debug container with ephemeral containers (K8s 1.23+)
kubectl debug my-pod -it --image=busybox --target=my-container

# Copy files from container (works with containerd)
kubectl cp my-pod:/path/to/file ./local-file

# Get container runtime info
kubectl get nodes -o wide

Resource Usage and Performance

# Get resource usage for nodes
kubectl top nodes

# Get resource usage for pods
kubectl top pods --all-namespaces --sort-by=memory

# Get pod metrics with labels
kubectl top pods -l app=nginx

# Resource quotas and limits
kubectl describe resourcequota -n my-namespace

Modern YAML Management

Using kubectl convert Plugin

# Install convert plugin
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl-convert"
chmod +x kubectl-convert
sudo mv kubectl-convert /usr/local/bin/

# Convert deprecated API versions
kubectl convert -f old-deployment.yaml --output-version apps/v1

# Batch convert all YAML files
find . -name "*.yaml" -exec kubectl convert -f {} \;

Dry Run and Diff

# Client-side dry run (validation only)
kubectl apply -f deployment.yaml --dry-run=client

# Server-side dry run (full validation)
kubectl apply -f deployment.yaml --dry-run=server

# Diff before applying
kubectl diff -f deployment.yaml

# Generate YAML from imperative commands
kubectl create deployment nginx --image=nginx:latest \
  --dry-run=client -o yaml > nginx-deployment.yaml

GitOps Workflows

Declarative Management Best Practices

# Apply all configs in a directory
kubectl apply -f ./configs/ --recursive

# Apply with pruning (remove deleted resources)
kubectl apply -f ./configs/ --prune --all

# Apply with field manager
kubectl apply -f deployment.yaml --field-manager=ci-pipeline

# Server-side apply (recommended for GitOps)
kubectl apply -f deployment.yaml --server-side

Kustomization Support

# Apply kustomization
kubectl apply -k ./overlays/production/

# Build and view kustomization
kubectl kustomize ./overlays/production/

# Diff kustomization
kubectl diff -k ./overlays/production/

Cloud Provider Integration

AWS EKS Integration

# Update kubeconfig for EKS
aws eks update-kubeconfig --region us-west-2 --name my-cluster

# Get EKS addon versions
aws eks describe-addon-versions --kubernetes-version 1.33

# EKS specific kubectl
curl -o kubectl https://s3.us-west-2.amazonaws.com/amazon-eks/1.33.0/2024-01-04/bin/linux/amd64/kubectl

GKE Integration

# Get GKE credentials
gcloud container clusters get-credentials my-cluster --zone us-central1-a

# GKE specific operations
kubectl top nodes --heapster-namespace=kube-system

AKS Integration

# Get AKS credentials
az aks get-credentials --resource-group myRG --name myCluster

# Enable AKS monitoring
kubectl apply -f https://raw.githubusercontent.com/microsoft/OMS-docker/aks/omsagent.yaml

Security Best Practices 2025

RBAC and Security Context

# Check current permissions
kubectl auth can-i create pods

# Check permissions as another user
kubectl auth can-i create pods --as=jane

# Check all permissions
kubectl auth can-i '*' '*'

# Get security context
kubectl get pods my-pod -o jsonpath='{.spec.securityContext}'

Secret Management

# Create secret from literal
kubectl create secret generic my-secret \
  --from-literal=username=admin \
  --from-literal=password='S3cur3P@ss'

# Create secret from file
kubectl create secret generic ssh-key \
  --from-file=id_rsa=~/.ssh/id_rsa

# Decode secret
kubectl get secret my-secret -o jsonpath='{.data.password}' | base64 -d

Advanced Troubleshooting

Pod Debugging Workflow

# 1. Check pod status
kubectl get pod my-pod -o wide

# 2. Describe for events
kubectl describe pod my-pod

# 3. Check logs
kubectl logs my-pod --previous  # Previous container logs
kubectl logs my-pod -c my-container --tail=100 -f

# 4. Debug with ephemeral container
kubectl debug my-pod -it --image=nicolaka/netshoot

# 5. Check resource constraints
kubectl top pod my-pod
kubectl describe node $(kubectl get pod my-pod -o jsonpath='{.spec.nodeName}')

Network Debugging

# Test connectivity from pod
kubectl run tmp-shell --rm -i --tty --image nicolaka/netshoot -- /bin/bash

# Port forwarding for debugging
kubectl port-forward pod/my-pod 8080:80

# Get service endpoints
kubectl get endpoints my-service

# Test DNS resolution
kubectl exec -it my-pod -- nslookup kubernetes.default

Performance Optimization

Resource Management

# Set resource requests/limits
kubectl set resources deployment nginx \
  --limits=cpu=200m,memory=512Mi \
  --requests=cpu=100m,memory=256Mi

# Autoscaling
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80

# Check HPA status
kubectl get hpa

Batch Operations

# Delete multiple resources
kubectl delete pods -l app=test --grace-period=0 --force

# Scale multiple deployments
kubectl scale --replicas=3 deployment/app1 deployment/app2

# Patch multiple resources
kubectl get pods -o name | xargs -I {} kubectl label {} environment=dev

Modern Context and Namespace Management

Using kubectx and kubens (2025 Edition)

# Install modern tools
brew install kubectx  # includes kubens
brew install kubecolor  # Colorized kubectl output
brew install stern  # Multi-pod log tailing

# Context switching
kubectx prod  # Switch to prod context
kubectx -  # Switch to previous context

# Namespace switching
kubens monitoring  # Switch to monitoring namespace
kubens -  # Switch to previous namespace

Advanced Context Management

# Create context with namespace
kubectl config set-context dev --cluster=dev-cluster \
  --user=dev-user --namespace=development

# Set default namespace for context
kubectl config set-context --current --namespace=production

# View merged kubeconfig
kubectl config view --merge --flatten > ~/.kube/config-merged

Useful Aliases and Functions

Add these to your shell configuration:

# ~/.zshrc or ~/.bashrc

# Quick pod shell access
ksh() {
  kubectl exec -it "$1" -- /bin/sh
}

# Quick pod bash access
kbash() {
  kubectl exec -it "$1" -- /bin/bash
}

# Get pod by partial name
kpod() {
  kubectl get pods | grep "$1" | head -1 | awk '{print $1}'
}

# Logs with grep
klogs() {
  kubectl logs "$1" | grep "$2"
}

# Force delete pod
kfdel() {
  kubectl delete pod "$1" --grace-period=0 --force
}

# Get all resources
kall() {
  kubectl api-resources --verbs=list --namespaced -o name \
    | xargs -n 1 kubectl get --show-kind --ignore-not-found
}

Best Practices Summary

  1. Version Alignment: Keep kubectl within one minor version of cluster
  2. Use Dry Run: Always validate with --dry-run=server before applying
  3. GitOps Ready: Use declarative configs and kubectl apply
  4. Security First: Verify checksums and use RBAC properly
  5. Debug Smart: Use ephemeral containers and proper tools
  6. Monitor Resources: Regular kubectl top checks
  7. Automate Common Tasks: Use aliases and functions
  8. Stay Updated: Use kubectl convert for API migrations

About Cloudurable

We hope you enjoyed this updated kubectl cheat sheet. Please provide feedback.

Cloudurable provides:


Last updated: January 2025 for Kubernetes 1.33

                                                                           
comments powered by Disqus

Apache Spark Training
Kafka Tutorial
Akka Consulting
Cassandra Training
AWS Cassandra Database Support
Kafka Support Pricing
Cassandra Database Support Pricing
Non-stop Cassandra
Watchdog
Advantages of using Cloudurable™
Cassandra Consulting
Cloudurable™| Guide to AWS Cassandra Deploy
Cloudurable™| AWS Cassandra Guidelines and Notes
Free guide to deploying Cassandra on AWS
Kafka Training
Kafka Consulting
DynamoDB Training
DynamoDB Consulting
Kinesis Training
Kinesis Consulting
Kafka Tutorial PDF
Kubernetes Security Training
Redis Consulting
Redis Training
ElasticSearch / ELK Consulting
ElasticSearch Training
InfluxDB/TICK Training TICK Consulting