kubectl Overview
kubectl is the command-line tool for communicating with a Kubernetes cluster's control plane via the Kubernetes API. It is the primary interface for managing all Kubernetes resources. Mastering kubectl is essential for every Kubernetes practitioner.
kubectl Command Structure
The basic syntax is: kubectl [command] [TYPE] [NAME] [flags]
- command: Operation — get, create, apply, delete, describe, logs, exec
- TYPE: Resource type — pod, service, deployment, configmap, secret
- NAME: Resource name (optional — omit to list all)
- flags: Options — -n namespace, -o output format, -l label selector
Context and Configuration
# View current context
kubectl config current-context
# List all contexts
kubectl config get-contexts
# Switch context
kubectl config use-context production-cluster
# Set default namespace for current context
kubectl config set-context --current --namespace=production
# View full kubeconfig
kubectl config view
# Merge kubeconfig files
KUBECONFIG=~/.kube/config:~/new-cluster.yaml kubectl config view --merge --flatten > ~/.kube/merged-config
mv ~/.kube/merged-config ~/.kube/config
Essential Commands
Getting Resources
# List resources
kubectl get pods
kubectl get pods -n production
kubectl get pods -A # All namespaces
kubectl get pods -l app=api-server # By label
kubectl get pods --field-selector status.phase=Running
# Wide output with extra info
kubectl get pods -o wide
# YAML output
kubectl get pod my-pod -o yaml
# JSON output
kubectl get pod my-pod -o json
# Custom columns
kubectl get pods -o custom-columns='NAME:.metadata.name,STATUS:.status.phase,IP:.status.podIP,NODE:.spec.nodeName'
# JSONPath for specific fields
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
# Sort by field
kubectl get pods --sort-by=.metadata.creationTimestamp
kubectl get pods --sort-by=.status.startTime
# Watch for changes in real time
kubectl get pods -w
Describing and Inspecting
# Detailed info about a resource
kubectl describe pod my-pod
kubectl describe deployment api-server
kubectl describe node worker-node-1
# View events (recent activity)
kubectl get events --sort-by=.lastTimestamp
kubectl get events -n production --field-selector reason=Failed
# Explain a resource type and its fields
kubectl explain pod.spec.containers.resources
kubectl explain deployment.spec.strategy
Creating and Modifying
# Apply manifests (declarative)
kubectl apply -f deployment.yaml
kubectl apply -f ./manifests/ # Apply all files in a directory
kubectl apply -f https://raw.githubusercontent.com/... # Apply from URL
# Create resources (imperative)
kubectl create deployment nginx --image=nginx:1.25 --replicas=3
kubectl create service clusterip my-svc --tcp=80:8080
kubectl create configmap app-config --from-literal=key=value
kubectl create secret generic db-pass --from-literal=password=secret
# Edit a resource in your editor
kubectl edit deployment api-server -n production
# Patch a resource
kubectl patch deployment api-server -n production -p '{"spec":{"replicas":5}}'
# Label resources
kubectl label pods my-pod environment=production
kubectl label pods -l app=api tier=backend
# Annotate resources
kubectl annotate deployment api-server description="Main API server"
Debugging
# View container logs
kubectl logs my-pod
kubectl logs my-pod -c sidecar-container # Specific container
kubectl logs my-pod --previous # Previous container (after crash)
kubectl logs -l app=api-server --all-containers # All pods matching label
kubectl logs my-pod -f # Follow/stream logs
kubectl logs my-pod --tail=100 # Last 100 lines
kubectl logs my-pod --since=1h # Last hour
# Execute commands in a container
kubectl exec my-pod -- ls /app
kubectl exec -it my-pod -- /bin/sh # Interactive shell
kubectl exec -it my-pod -c web -- bash # Specific container
# Port forwarding
kubectl port-forward pod/my-pod 8080:3000
kubectl port-forward svc/api-service 8080:80
kubectl port-forward deployment/api-server 8080:3000
# Copy files to/from a container
kubectl cp my-pod:/var/log/app.log ./app.log
kubectl cp ./config.yaml my-pod:/app/config.yaml
# Run a debug pod
kubectl run debug --image=busybox --rm -it -- /bin/sh
kubectl run debug --image=nicolaka/netshoot --rm -it -- /bin/bash
# Debug a node
kubectl debug node/worker-node-1 -it --image=busybox
# Top (resource usage)
kubectl top pods -n production
kubectl top nodes
Productivity Tips
# Shell aliases (add to ~/.bashrc or ~/.zshrc)
alias k='kubectl'
alias kgp='kubectl get pods'
alias kgs='kubectl get services'
alias kgd='kubectl get deployments'
alias kga='kubectl get all'
alias kdp='kubectl describe pod'
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias kns='kubectl config set-context --current --namespace'
# Enable kubectl autocompletion
source <(kubectl completion bash) # bash
source <(kubectl completion zsh) # zsh
# Dry run to generate YAML
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml
kubectl create service clusterip my-svc --tcp=80:8080 --dry-run=client -o yaml > service.yaml
# Diff before applying
kubectl diff -f deployment.yaml
Key Takeaways
- Master context management to switch between clusters and namespaces efficiently
- Use -o yaml, -o json, and -o jsonpath for flexible output formatting
- kubectl logs, exec, and port-forward are essential debugging tools
- Use --dry-run=client -o yaml to generate YAML templates from imperative commands
- Set up shell aliases and autocompletion for 10x productivity