kubectl: Essential Commands - Complete Reference Guide

kubectl is the command-line tool for interacting with Kubernetes clusters. Mastering kubectl is essential for managing Kubernetes resources, debugging applications, and performing day-to-day cluster operations. This comprehensive guide covers all essential kubectl commands with practical examples and best practices.

Table of Contents

Introduction

kubectl (Kube Control) communicates with the Kubernetes API server to execute commands. Understanding kubectl syntax and common operations is fundamental for Kubernetes administration.

kubectl Syntax

kubectl [command] [TYPE] [NAME] [flags]

# Examples:
kubectl get pods
kubectl describe pod my-pod
kubectl delete deployment nginx
kubectl logs pod-name --tail=100

Getting Help

# General help
kubectl help
kubectl --help

# Command-specific help
kubectl get --help
kubectl create --help

# Explain resource
kubectl explain pods
kubectl explain deployment.spec

Configuration and Context

Viewing Configuration

# Show current context
kubectl config current-context

# View all contexts
kubectl config get-contexts

# View config file
kubectl config view

# View config with secrets
kubectl config view --raw

Managing Contexts

# Switch context
kubectl config use-context my-context

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

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

# Rename context
kubectl config rename-context old-name new-name

# Delete context
kubectl config delete-context my-context

Multiple Clusters

# Specify kubeconfig file
kubectl --kubeconfig=/path/to/config get pods

# Set KUBECONFIG environment variable
export KUBECONFIG=~/.kube/config:~/.kube/config-cluster2

# Merge kubeconfig files
KUBECONFIG=~/.kube/config:~/.kube/config2 kubectl config view --flatten > ~/.kube/merged-config

Resource Management

Getting Resources

# List all pods
kubectl get pods

# All namespaces
kubectl get pods -A
kubectl get pods --all-namespaces

# Specific namespace
kubectl get pods -n kube-system

# With labels
kubectl get pods --show-labels

# Filter by label
kubectl get pods -l app=nginx
kubectl get pods -l 'environment in (production,staging)'

# Wide output (more details)
kubectl get pods -o wide

# Custom output format
kubectl get pods -o json
kubectl get pods -o yaml
kubectl get pods -o name

Describing Resources

# Detailed information
kubectl describe pod my-pod
kubectl describe service my-service
kubectl describe deployment my-deployment

# Describe all pods
kubectl describe pods

# Describe in specific namespace
kubectl describe pod my-pod -n my-namespace

Creating Resources

# From file
kubectl create -f pod.yaml
kubectl apply -f deployment.yaml

# From directory
kubectl apply -f ./manifests/

# From URL
kubectl apply -f https://example.com/deployment.yaml

# Create deployment imperatively
kubectl create deployment nginx --image=nginx:alpine

# Create service
kubectl create service clusterip my-service --tcp=80:8080

# Dry-run (test without creating)
kubectl create deployment test --image=nginx --dry-run=client -o yaml

Updating Resources

# Apply changes from file
kubectl apply -f deployment.yaml

# Edit resource in editor
kubectl edit deployment nginx

# Patch resource
kubectl patch deployment nginx -p '{"spec":{"replicas":5}}'

# Set image
kubectl set image deployment/nginx nginx=nginx:1.26

# Set resources
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi

Deleting Resources

# Delete specific resource
kubectl delete pod my-pod
kubectl delete deployment my-deployment

# Delete from file
kubectl delete -f deployment.yaml

# Delete all pods with label
kubectl delete pods -l app=nginx

# Delete all resources in namespace
kubectl delete all --all -n my-namespace

# Force delete
kubectl delete pod my-pod --force --grace-period=0

# Delete namespace (cascade deletes all resources)
kubectl delete namespace my-namespace

Pods and Containers

Viewing Pods

# List pods
kubectl get pods

# Watch pods (live updates)
kubectl get pods -w
kubectl get pods --watch

# Sort by creation time
kubectl get pods --sort-by=.metadata.creationTimestamp

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

# Show resource usage
kubectl top pods
kubectl top pods --containers

Running Pods

# Run single pod
kubectl run nginx --image=nginx:alpine

# Run with custom command
kubectl run busybox --image=busybox --command -- sleep 3600

# Run interactive pod
kubectl run -it debug --image=busybox --rm -- sh

# Run with environment variables
kubectl run nginx --image=nginx --env="ENV=production"

# Run with labels
kubectl run nginx --image=nginx --labels="app=web,env=prod"

# Run with resource limits
kubectl run nginx --image=nginx --requests='cpu=100m,memory=256Mi' --limits='cpu=200m,memory=512Mi'

Accessing Pods

# View logs
kubectl logs my-pod

# Follow logs
kubectl logs -f my-pod

# Last 100 lines
kubectl logs my-pod --tail=100

# Logs from previous container
kubectl logs my-pod --previous

# Logs from specific container
kubectl logs my-pod -c container-name

# Logs with timestamps
kubectl logs my-pod --timestamps

# Execute command in pod
kubectl exec my-pod -- ls /app

# Interactive shell
kubectl exec -it my-pod -- bash
kubectl exec -it my-pod -- sh

# Execute in specific container
kubectl exec -it my-pod -c container-name -- sh

Port Forwarding

# Forward local port to pod
kubectl port-forward pod/my-pod 8080:80

# Forward to service
kubectl port-forward service/my-service 8080:80

# Forward to deployment
kubectl port-forward deployment/nginx 8080:80

# Listen on all interfaces
kubectl port-forward --address 0.0.0.0 pod/my-pod 8080:80

Copying Files

# Copy from pod to local
kubectl cp my-pod:/path/to/file ./local-file

# Copy from local to pod
kubectl cp ./local-file my-pod:/path/to/file

# Copy from specific container
kubectl cp my-pod:/path/to/file ./local-file -c container-name

# Copy directory
kubectl cp my-pod:/app/logs ./logs/

Deployments and Scaling

Managing Deployments

# List deployments
kubectl get deployments

# Create deployment
kubectl create deployment nginx --image=nginx:alpine --replicas=3

# Scale deployment
kubectl scale deployment nginx --replicas=5

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

# View autoscaler
kubectl get hpa

Rolling Updates

# Update image
kubectl set image deployment/nginx nginx=nginx:1.26-alpine

# Update with record
kubectl set image deployment/nginx nginx=nginx:1.26 --record

# View rollout status
kubectl rollout status deployment/nginx

# View rollout history
kubectl rollout history deployment/nginx

# View specific revision
kubectl rollout history deployment/nginx --revision=2

# Pause rollout
kubectl rollout pause deployment/nginx

# Resume rollout
kubectl rollout resume deployment/nginx

# Undo rollout
kubectl rollout undo deployment/nginx

# Rollback to specific revision
kubectl rollout undo deployment/nginx --to-revision=2

# Restart deployment
kubectl rollout restart deployment/nginx

Services and Networking

Managing Services

# List services
kubectl get services
kubectl get svc

# Create ClusterIP service
kubectl create service clusterip my-service --tcp=80:8080

# Create NodePort service
kubectl create service nodeport my-service --tcp=80:8080 --node-port=30080

# Expose deployment as service
kubectl expose deployment nginx --port=80 --target-port=8080

# Expose with type
kubectl expose deployment nginx --type=NodePort --port=80

Service Endpoints

# View service endpoints
kubectl get endpoints my-service

# Describe endpoints
kubectl describe endpoints my-service

Ingress

# List ingress resources
kubectl get ingress

# Describe ingress
kubectl describe ingress my-ingress

# Create ingress
kubectl create ingress my-ingress \
  --rule="example.com/*=my-service:80"

ConfigMaps and Secrets

ConfigMaps

# Create from literal
kubectl create configmap app-config \
  --from-literal=database_url=postgres://db:5432 \
  --from-literal=log_level=info

# Create from file
kubectl create configmap app-config --from-file=config.properties

# Create from directory
kubectl create configmap app-config --from-file=./config/

# View ConfigMap
kubectl get configmap app-config
kubectl describe configmap app-config
kubectl get configmap app-config -o yaml

# Edit ConfigMap
kubectl edit configmap app-config

# Delete ConfigMap
kubectl delete configmap app-config

Secrets

# Create secret from literal
kubectl create secret generic db-secret \
  --from-literal=username=admin \
  --from-literal=password=secret123

# Create secret from file
kubectl create secret generic tls-secret \
  --from-file=tls.crt=./cert.pem \
  --from-file=tls.key=./key.pem

# Create TLS secret
kubectl create secret tls tls-secret \
  --cert=./cert.pem \
  --key=./key.pem

# Create Docker registry secret
kubectl create secret docker-registry regcred \
  --docker-server=registry.example.com \
  --docker-username=user \
  --docker-password=pass \
  [email protected]

# View secrets
kubectl get secrets
kubectl describe secret db-secret

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

# Delete secret
kubectl delete secret db-secret

Troubleshooting Commands

Cluster Information

# Cluster info
kubectl cluster-info

# View cluster components
kubectl get componentstatuses
kubectl get cs

# View nodes
kubectl get nodes
kubectl describe node node-name
kubectl top nodes

Events

# View all events
kubectl get events

# Sort by timestamp
kubectl get events --sort-by='.lastTimestamp'

# Events in specific namespace
kubectl get events -n kube-system

# Watch events
kubectl get events -w

Resource Usage

# Node metrics
kubectl top nodes

# Pod metrics
kubectl top pods

# Pod metrics in namespace
kubectl top pods -n kube-system

# Container metrics
kubectl top pods --containers

# Metrics for specific pod
kubectl top pod my-pod

Debugging

# Debug pod
kubectl debug my-pod -it --image=busybox

# Debug node
kubectl debug node/node-name -it --image=busybox

# Run debug container in existing pod
kubectl debug my-pod --image=busybox --target=container-name

# Attach to pod
kubectl attach my-pod -i

# Show pod processes
kubectl top pods --containers

Advanced Operations

Labels and Annotations

# Add label
kubectl label pods my-pod environment=production

# Update label
kubectl label pods my-pod environment=staging --overwrite

# Remove label
kubectl label pods my-pod environment-

# Add annotation
kubectl annotate pods my-pod description="Web server pod"

# Remove annotation
kubectl annotate pods my-pod description-

Resource Filtering

# Field selectors
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=node-1

# Label selectors
kubectl get pods -l app=nginx
kubectl get pods -l 'app in (nginx,apache)'
kubectl get pods -l app=nginx,env=prod

# Multiple conditions
kubectl get pods --field-selector status.phase=Running -l app=nginx

YAML and JSON Output

# Get YAML
kubectl get pod my-pod -o yaml

# Get JSON
kubectl get pod my-pod -o json

# JSONPath (specific fields)
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{.items[*].status.podIP}'

# Custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP

# Go template
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'

API Resources

# List all API resources
kubectl api-resources

# List resources with short names
kubectl api-resources -o wide

# List namespaced resources
kubectl api-resources --namespaced=true

# List cluster-wide resources
kubectl api-resources --namespaced=false

# Get API versions
kubectl api-versions

Plugin Management

# List plugins
kubectl plugin list

# Install krew (plugin manager)
kubectl krew install krew

# Install plugins with krew
kubectl krew install ctx
kubectl krew install ns

# Use plugins
kubectl ctx  # List contexts
kubectl ns   # List namespaces

Productivity Tips

Aliases and Functions

# Add to ~/.bashrc or ~/.zshrc

# Basic aliases
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kdel='kubectl delete'
alias kl='kubectl logs'
alias ke='kubectl exec -it'

# Advanced aliases
alias kgp='kubectl get pods'
alias kgs='kubectl get services'
alias kgd='kubectl get deployments'
alias kgn='kubectl get nodes'

# Function for namespace switching
kns() {
  kubectl config set-context --current --namespace=$1
}

# Function for quick pod logs
klf() {
  kubectl logs -f $1
}

Bash Completion

# Install bash-completion
sudo apt-get install bash-completion

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

# For zsh
echo 'source <(kubectl completion zsh)' >> ~/.zshrc

Useful Shortcuts

# Short resource names
k get po      # pods
k get svc     # services
k get deploy  # deployments
k get rs      # replicasets
k get cm      # configmaps
k get ns      # namespaces

# Quick pod shell access
k exec -it <pod> -- sh

# Quick service test
k run curl --image=curlimages/curl --rm -it -- curl http://service-name

Conclusion

Mastering kubectl is essential for effective Kubernetes cluster management. These commands form the foundation of day-to-day operations, troubleshooting, and automation.

Key Takeaways

  • Context Management: Switch between clusters and namespaces efficiently
  • Resource Operations: Create, read, update, delete resources
  • Debugging: Logs, exec, describe, events for troubleshooting
  • Productivity: Use aliases, completion, and shortcuts
  • Advanced: JSONPath, filtering, and API exploration

Essential Command Reference

# Configuration
kubectl config current-context
kubectl config use-context <context>
kubectl config set-context --current --namespace=<ns>

# Resources
kubectl get <resource>
kubectl describe <resource> <name>
kubectl create -f <file>
kubectl apply -f <file>
kubectl delete <resource> <name>

# Pods
kubectl get pods
kubectl logs <pod>
kubectl exec -it <pod> -- sh
kubectl port-forward <pod> 8080:80

# Deployments
kubectl scale deployment <name> --replicas=<num>
kubectl set image deployment/<name> container=image:tag
kubectl rollout status deployment/<name>
kubectl rollout undo deployment/<name>

# Troubleshooting
kubectl describe pod <name>
kubectl logs -f <pod>
kubectl get events --sort-by='.lastTimestamp'
kubectl top pods

Next Steps

  1. Practice: Use kubectl daily for familiarity
  2. Automation: Write scripts and use kubectl in CI/CD
  3. Customize: Create personal aliases and functions
  4. Explore: Try kubectl plugins via krew
  5. Monitor: Combine with monitoring tools
  6. Learn: Study JSONPath and Go templates
  7. Contribute: Extend kubectl with custom plugins

kubectl is your primary interface to Kubernetes. Master it to become proficient in cluster management!