kubectl — Control Kubernetes Clusters from the Command Line
Practical guide to kubectl — manage pods, deployments, services and clusters, read logs, steer rollouts and debug, with examples for every command.
kubectl is the primary command-line tool for Kubernetes: every command talks to the cluster's API server through your kubeconfig and manages pods, deployments, services and every other resource. Which cluster you target is set by the active context, so you can switch between development and production with a single command. This guide walks you through the commands you reach for daily: viewing and applying resources, steering rollouts, reading logs and debugging inside a running pod.
Cluster & Context
kubectl cluster-info — Display cluster endpoint information.
kubectl cluster-infokubectl config get-contexts — List all available contexts (clusters).
kubectl config get-contextskubectl config current-context — Show the currently active context.
kubectl config current-contextkubectl config use-context <name> — Switch to a different context (cluster).
kubectl config use-context productionkubectl config set-context --current --namespace=<ns> — Set the default namespace for the current context.
kubectl config set-context --current --namespace=my-appkubectl version — Show the client and server version.
kubectl version -o yamlkubectl api-resources — List all available resource types and their short names.
kubectl api-resourcesViewing Resources
kubectl get <resource> — List resources of a given type in the current namespace.
kubectl get podskubectl get <resource> -A — List resources across all namespaces.
kubectl get pods -Akubectl get <resource> -n <namespace> — List resources in a specific namespace.
kubectl get pods -n productionkubectl get <resource> -o wide — Show additional details like node and IP.
kubectl get pods -o widekubectl get <resource> -o yaml — Output the resource definition as YAML.
kubectl get deployment nginx -o yamlkubectl get <resource> -o json — Output the resource definition as JSON.
kubectl get pod my-pod -o jsonkubectl get all — List all common resources (pods, services, deployments, etc.).
kubectl get all -n my-appkubectl describe <resource> <name> — Show detailed information about a specific resource including events.
kubectl describe pod my-podkubectl get <resource> -l <label>=<value> — Filter resources by label selector.
kubectl get pods -l app=nginxkubectl get <resource> --sort-by=<field> — Sort output by a specific field.
kubectl get pods --sort-by=.metadata.creationTimestampCreating & Applying
kubectl apply -f <file> — Create or update resources defined in a YAML/JSON file.
kubectl apply -f deployment.yamlkubectl apply -f <directory> — Apply all resource files in a directory.
kubectl apply -f ./k8s/kubectl apply -f <url> — Apply a resource from a remote URL.
kubectl apply -f https://raw.githubusercontent.com/org/repo/main/deploy.yamlkubectl create deployment <name> --image=<image> — Create a deployment imperatively.
kubectl create deployment nginx --image=nginx:alpinekubectl create namespace <name> — Create a new namespace.
kubectl create namespace stagingkubectl run <name> --image=<image> — Create and run a pod.
kubectl run debug --image=busybox --rm -it -- shkubectl expose deployment <name> --port=<port> --type=<type> — Create a service for a deployment.
kubectl expose deployment nginx --port=80 --type=LoadBalancerEditing & Updating
kubectl edit <resource> <name> — Edit a resource in your default editor.
kubectl edit deployment nginxkubectl set image deployment/<name> <container>=<image> — Update the image of a container in a deployment.
kubectl set image deployment/nginx nginx=nginx:1.25kubectl scale deployment <name> --replicas=<n> — Scale a deployment to n replicas.
kubectl scale deployment nginx --replicas=5kubectl rollout status deployment/<name> — Watch the rollout status of a deployment.
kubectl rollout status deployment/nginxkubectl rollout history deployment/<name> — View the rollout history (revisions) of a deployment.
kubectl rollout history deployment/nginxkubectl rollout undo deployment/<name> — Rollback a deployment to the previous revision.
kubectl rollout undo deployment/nginxkubectl rollout undo deployment/<name> --to-revision=<n> — Rollback to a specific revision number.
kubectl rollout undo deployment/nginx --to-revision=3kubectl label <resource> <name> <key>=<value> — Add or update a label on a resource.
kubectl label pod my-pod env=productionkubectl annotate <resource> <name> <key>=<value> — Add or update an annotation on a resource.
kubectl annotate deployment nginx description='Web server'kubectl patch <resource> <name> -p '<json>' — Update specific fields of a resource using a JSON patch.
kubectl patch deployment nginx -p '{"spec":{"replicas":3}}'Deleting Resources
kubectl delete <resource> <name> — Delete a specific resource by name.
kubectl delete pod my-podkubectl delete -f <file> — Delete all resources defined in a file.
kubectl delete -f deployment.yamlkubectl delete <resource> -l <label>=<value> — Delete all resources matching a label selector.
kubectl delete pods -l app=old-versionkubectl delete namespace <name> — Delete a namespace and all resources within it.
kubectl delete namespace stagingkubectl delete pod <name> --grace-period=0 --force — Force delete a stuck pod immediately.
kubectl delete pod stuck-pod --grace-period=0 --forceLogs & Debugging
kubectl logs <pod> — Print the logs of a pod.
kubectl logs my-podkubectl logs -f <pod> — Stream (follow) the logs of a pod in real time.
kubectl logs -f my-podkubectl logs <pod> -c <container> — Print logs from a specific container in a multi-container pod.
kubectl logs my-pod -c sidecarkubectl logs <pod> --previous — Print logs from the previous instance of a container (after a crash).
kubectl logs my-pod --previouskubectl logs -l <label>=<value> — Print logs from all pods matching a label.
kubectl logs -l app=nginx --all-containerskubectl logs <pod> --tail=<n> — Show only the last n lines of logs.
kubectl logs my-pod --tail=50kubectl logs <pod> --since=<duration> — Show logs from the last duration (e.g., 1h, 30m).
kubectl logs my-pod --since=1hkubectl exec -it <pod> -- <command> — Execute an interactive command in a running pod.
kubectl exec -it my-pod -- /bin/bashkubectl exec <pod> -- <command> — Execute a non-interactive command in a pod.
kubectl exec my-pod -- cat /etc/config.yamlkubectl top pods — Show CPU and memory usage for pods (requires metrics-server).
kubectl top pods -n my-appkubectl top nodes — Show CPU and memory usage for nodes.
kubectl top nodeskubectl get events --sort-by=.lastTimestamp — View cluster events sorted by time (useful for debugging).
kubectl get events --sort-by=.lastTimestamp -n my-appPort Forwarding & Proxy
kubectl port-forward <pod> <local>:<remote> — Forward a local port to a port on a pod.
kubectl port-forward my-pod 8080:80kubectl port-forward svc/<service> <local>:<remote> — Forward a local port to a service.
kubectl port-forward svc/my-service 3000:80kubectl proxy — Start a proxy to the Kubernetes API server on localhost:8001.
kubectl proxyCopying Files
kubectl cp <pod>:<path> <local_path> — Copy a file from a pod to the local filesystem.
kubectl cp my-pod:/var/log/app.log ./app.logkubectl cp <local_path> <pod>:<path> — Copy a local file into a pod.
kubectl cp ./config.yaml my-pod:/app/config.yamlkubectl cp <ns>/<pod>:<path> <local_path> — Copy from a pod in a specific namespace.
kubectl cp production/my-pod:/data/export.csv ./export.csvSecrets & ConfigMaps
kubectl create secret generic <name> --from-literal=<key>=<value> — Create a secret from literal key-value pairs.
kubectl create secret generic db-creds --from-literal=username=admin --from-literal=password=s3cretkubectl create secret generic <name> --from-file=<path> — Create a secret from a file.
kubectl create secret generic tls-cert --from-file=cert.pem --from-file=key.pemkubectl get secret <name> -o jsonpath='{.data.<key>}' | base64 -d — Decode and display a secret value.
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -dkubectl create configmap <name> --from-literal=<key>=<value> — Create a ConfigMap from literal key-value pairs.
kubectl create configmap app-config --from-literal=APP_ENV=productionkubectl create configmap <name> --from-file=<path> — Create a ConfigMap from a file or directory.
kubectl create configmap nginx-conf --from-file=nginx.conf Conclusion
kubectl is the hub of day-to-day cluster work: from a quick get to a targeted rollout undo, you handle almost any task without a dashboard. If you use it regularly, set up an alias (k for kubectl), shell completion and --dry-run=client -o yaml for clean GitOps – turning single commands into a reproducible workflow.
Further Reading
- kubectl – official reference – every command and option in detail
- kubectl Quick Reference – compact command overview
- Kubernetes – Wikipedia – background and architecture
Related Commands
- ddev – local PHP development environments with Docker
- docker – build and run individual containers
- docker-compose – orchestrate multi-container apps locally