Kubectl
Website: https://kubernetes.io
CLI Tool: kubectl
Authentication: kubectl config use-context
Description
kubectl is the Kubernetes command-line tool for controlling Kubernetes clusters. It communicates with the Kubernetes API server to deploy applications, inspect and manage cluster resources, and view logs. Essential for container orchestration and cloud-native application management.
Commands
Cluster Information
Cluster Info
kubectl cluster-info
kubectl cluster-info dump
Display cluster endpoint information. Use dump for detailed cluster state.
Version
kubectl version
kubectl version --short
Show client and server Kubernetes versions.
Context Management
kubectl config get-contexts
kubectl config current-context
kubectl config use-context <context-name>
kubectl config set-context <context-name> --namespace=<namespace>
Manage kubectl contexts for multiple clusters.
Resource Management
Get Resources
kubectl get <resource>
kubectl get pods
kubectl get pods -o wide
kubectl get pods -o yaml
kubectl get pods -o json
kubectl get pods --all-namespaces
kubectl get pods -n <namespace>
kubectl get pods -l app=myapp
kubectl get all
List resources. Use -o for output format, -n for namespace, -l for label selector, --all-namespaces for all namespaces.
Describe Resources
kubectl describe <resource> <name>
kubectl describe pod myapp-pod
kubectl describe node node-1
kubectl describe service myapp-service
Show detailed information about a resource.
Create Resources
kubectl create -f <file>
kubectl create -f deployment.yaml
kubectl create deployment nginx --image=nginx
kubectl create service clusterip myapp --tcp=80:80
kubectl create namespace dev
kubectl create configmap myconfig --from-literal=key=value
kubectl create secret generic mysecret --from-literal=password=secret123
Create resources from file or command line.
Apply Configuration
kubectl apply -f <file>
kubectl apply -f deployment.yaml
kubectl apply -f . (apply all files in directory)
kubectl apply -k <directory> (kustomize)
Apply configuration to resources (declarative management).
Delete Resources
kubectl delete <resource> <name>
kubectl delete -f <file>
kubectl delete pod myapp-pod
kubectl delete deployment myapp
kubectl delete pods -l app=myapp
kubectl delete all --all
Delete resources by name, file, or label selector.
Edit Resources
kubectl edit <resource> <name>
kubectl edit deployment myapp
Edit resource in default editor.
Patch Resources
kubectl patch <resource> <name> -p '<patch>'
kubectl patch deployment myapp -p '{"spec":{"replicas":3}}'
Update resource fields using strategic merge patch.
Pods
Run Pod
kubectl run <name> --image=<image>
kubectl run nginx --image=nginx --port=80
kubectl run debug --image=busybox -it --rm -- sh
Run a pod. Use --rm for temporary pods, -it for interactive terminal.
Get Pod Logs
kubectl logs <pod-name>
kubectl logs -f <pod-name>
kubectl logs <pod-name> -c <container-name>
kubectl logs --previous <pod-name>
kubectl logs --tail=100 <pod-name>
kubectl logs -l app=myapp
View pod logs. Use -f to follow, -c for specific container, --previous for previous instance.
Execute Command in Pod
kubectl exec <pod-name> -- <command>
kubectl exec -it <pod-name> -- bash
kubectl exec <pod-name> -c <container> -- ls /app
Execute command in container. Use -it for interactive shell.
Port Forward
kubectl port-forward <pod-name> <local-port>:<pod-port>
kubectl port-forward pod/myapp 8080:80
kubectl port-forward service/myapp 8080:80
Forward local port to pod or service port.
Copy Files
kubectl cp <pod-name>:/path/to/file ./local/path
kubectl cp ./local/file <pod-name>:/path/to/destination
kubectl cp <namespace>/<pod>:/path/file ./local
Copy files to/from pod containers.
Deployments
Create Deployment
kubectl create deployment <name> --image=<image>
kubectl create deployment nginx --image=nginx:1.21
kubectl create deployment web --image=myapp --replicas=3
Create deployment with specified image.
Scale Deployment
kubectl scale deployment <name> --replicas=<count>
kubectl scale deployment myapp --replicas=5
kubectl autoscale deployment myapp --min=2 --max=10 --cpu-percent=80
Scale deployment replicas manually or with autoscaling.
Update Deployment
kubectl set image deployment/<name> <container>=<image>
kubectl set image deployment/myapp myapp=myapp:v2
kubectl rollout restart deployment/myapp
Update deployment image or restart.
Rollout Management
kubectl rollout status deployment/<name>
kubectl rollout history deployment/<name>
kubectl rollout undo deployment/<name>
kubectl rollout undo deployment/<name> --to-revision=2
Manage deployment rollouts and rollbacks.
Services
Expose Service
kubectl expose deployment <name> --port=<port> --target-port=<target-port>
kubectl expose deployment myapp --port=80 --target-port=8080 --type=LoadBalancer
kubectl expose pod myapp --port=80 --name=myapp-service
Create service to expose pods.
Get Endpoints
kubectl get endpoints
kubectl get endpoints <service-name>
List service endpoints.
ConfigMaps and Secrets
Create ConfigMap
kubectl create configmap <name> --from-literal=<key>=<value>
kubectl create configmap myconfig --from-file=config.txt
kubectl create configmap myconfig --from-env-file=.env
Create ConfigMap from literals, files, or env files.
Create Secret
kubectl create secret generic <name> --from-literal=<key>=<value>
kubectl create secret generic mysecret --from-file=secret.txt
kubectl create secret docker-registry regcred --docker-server=<server> --docker-username=<user> --docker-password=<pass>
kubectl create secret tls tls-secret --cert=cert.crt --key=cert.key
Create secrets for sensitive data.
Get ConfigMap/Secret Data
kubectl get configmap <name> -o yaml
kubectl get secret <name> -o jsonpath='{.data.password}' | base64 -d
View ConfigMap or Secret contents.
Namespaces
List Namespaces
kubectl get namespaces
kubectl get ns
List all namespaces.
Create Namespace
kubectl create namespace <name>
kubectl create ns dev
Create a new namespace.
Delete Namespace
kubectl delete namespace <name>
Delete namespace and all its resources.
Set Default Namespace
kubectl config set-context --current --namespace=<namespace>
Set default namespace for current context.
Resource Quotas and Limits
Resource Usage
kubectl top nodes
kubectl top pods
kubectl top pods -n <namespace>
kubectl top pods --containers
Show resource usage (requires metrics-server).
Jobs and CronJobs
Create Job
kubectl create job <name> --image=<image>
kubectl create job test --image=busybox -- echo "Hello"
Create a one-time job.
Create CronJob
kubectl create cronjob <name> --image=<image> --schedule="<cron>"
kubectl create cronjob backup --image=backup:latest --schedule="0 2 * * *"
Create scheduled job.
Debugging
Get Events
kubectl get events
kubectl get events --sort-by='.lastTimestamp'
kubectl get events -n <namespace>
View cluster events.
Debug Pod
kubectl debug <pod-name> -it --image=busybox
kubectl debug node/<node-name> -it --image=busybox
Create debugging container for troubleshooting.
Proxy
kubectl proxy
kubectl proxy --port=8080
Create proxy to Kubernetes API server.
Examples
Deploy Application
# Create deployment
kubectl create deployment myapp --image=myapp:v1 --replicas=3
# Expose as service
kubectl expose deployment myapp --port=80 --type=LoadBalancer
# Check status
kubectl get pods -l app=myapp
kubectl get service myapp
# View logs
kubectl logs -l app=myapp -f
Update Application
# Update image
kubectl set image deployment/myapp myapp=myapp:v2
# Watch rollout
kubectl rollout status deployment/myapp
# Check history
kubectl rollout history deployment/myapp
# Rollback if needed
kubectl rollout undo deployment/myapp
Debug Application
# Check pod status
kubectl get pods
kubectl describe pod myapp-abc123
# View logs
kubectl logs myapp-abc123
kubectl logs myapp-abc123 --previous
# Execute commands
kubectl exec -it myapp-abc123 -- sh
kubectl exec myapp-abc123 -- env
# Port forward for testing
kubectl port-forward myapp-abc123 8080:80
ConfigMap and Secret Usage
# Create ConfigMap
kubectl create configmap app-config \
--from-literal=db_host=localhost \
--from-literal=db_port=5432
# Create Secret
kubectl create secret generic app-secret \
--from-literal=db_password=secret123
# Use in deployment (apply from file)
kubectl apply -f deployment-with-config.yaml
Manage Multiple Environments
# Create namespaces
kubectl create namespace dev
kubectl create namespace staging
kubectl create namespace prod
# Deploy to specific namespace
kubectl apply -f deployment.yaml -n dev
# Switch default namespace
kubectl config set-context --current --namespace=dev
# View resources across all namespaces
kubectl get pods --all-namespaces
Notes
- Contexts: Use contexts to switch between clusters and namespaces
- Declarative Management: Prefer
kubectl applyoverkubectl createfor reproducibility - Labels: Use labels for resource organization and selection
- Namespaces: Isolate resources using namespaces
- YAML: Most resources are defined in YAML manifests
- Selectors: Use
-l key=valueto filter resources by labels - JSON Path: Use
-o jsonpathfor precise field extraction - Dry Run: Test changes with
--dry-run=client -o yaml - Force Delete: Use
--force --grace-period=0for stuck pods (use carefully) - API Resources: Run
kubectl api-resourcesto list all resource types - Explain: Use
kubectl explain <resource>for resource documentation - Completion: Enable shell completion with
kubectl completion bash|zsh - Plugins: Extend kubectl with plugins using Krew plugin manager
- Config: kubeconfig file location:
~/.kube/config
Comments (0)
Add a Comment
No comments yet. Be the first to comment!