kubectl Reference
kubectl is the primary command-line interface to Kubernetes. Every command you type is translated into an authenticated HTTPS request to the API server, which then orchestrates the rest of the cluster. This page covers how to configure it, how to use it effectively, and when to choose each management style.
Setting Up a Cluster
Section titled “Setting Up a Cluster”Before interacting with kubectl, you need a running cluster. You have two broad options: local (for development) and cloud-managed (for cloud-specific features and production scenarios).
Local Options
Section titled “Local Options”| Tool | Nodes | Notes |
|---|---|---|
| Docker Desktop | Multi-node (configurable) | Bundles Docker, Kubernetes, and kubectl. Nodes run as Docker containers. Free for personal/educational use; paid license required for companies >250 employees or >$10M revenue. |
| Minikube | Single-node | Spins up a Linux VM. Works on any OS. |
| Kind (Kubernetes in Docker) | Multi-node | Uses CRI-O, runs each node in a separate container. Easy to simulate real multi-node topologies. |
| k3d | Multi-node | Lightweight K3s wrapped in Docker containers. Fast startup, low overhead. |
| K3s | Single or multi-node | Production-grade single-binary Kubernetes by Rancher/SUSE. ~512MB RAM footprint. Go-to for edge, ARM, and resource-constrained environments. k3d wraps this in Docker. |
| MicroK8s | Single or multi-node | By Canonical — installs via snap. Supports built-in addons (DNS, dashboard, storage, GPU). Popular on Ubuntu and Raspberry Pi. |
| Rancher Desktop | Single-node | Open-source alternative to Docker Desktop — bundles K3s, containerd/dockerd, and kubectl. No licensing restrictions. |
Cloud-Managed Options
Section titled “Cloud-Managed Options”Cloud clusters are required for features like cloud load balancers and cloud storage integrations. Any major managed Kubernetes service works — GKE, EKS (AWS), AKS (Azure), DigitalOcean, Linode — and all follow the same pattern: the provider manages the control plane, you configure node pools via their CLI or console, and download a kubeconfig to connect with kubectl.
Manual deployment (setting up a multi-node cluster entirely from scratch) is highly complex due to networking and administration requirements. See Cluster Setup with kubeadm if you need to do this.
kubeconfig and Contexts
Section titled “kubeconfig and Contexts”kubectl reads a configuration file to know which cluster to talk to and how to authenticate.
The kubeconfig File
Section titled “The kubeconfig File”- Located at
~/.kube/config(macOS/Linux) orC:\Users\<username>\.kube\config(Windows) - The filename is exactly
config- no.yamlextension - Structured into four components:
| Component | Purpose |
|---|---|
| Clusters | List of known clusters and their API endpoints |
| Users | Credentials (certificates and private keys) |
| Contexts | Named pairings of a cluster + a user |
| Current context | The active context kubectl sends all commands to |
Version Compatibility
Section titled “Version Compatibility”Your kubectl version must be within one minor version of your cluster. If the cluster runs v1.32.x, use kubectl v1.31.x or v1.33.x.
Switching and Scoping Contexts
Section titled “Switching and Scoping Contexts”kubectl config get-contexts # list all contextskubectl config current-context # show active contextkubectl config use-context <context-name> # switch active context
# Set a default namespace for the current context# Avoids typing -n <namespace> on every commandkubectl config set-context --current --namespace=my-namespaceMerging Multiple Cluster Configs
Section titled “Merging Multiple Cluster Configs”When you need to add a second cluster (e.g., a cloud cluster) alongside an existing local one:
# 1. Rename your existing config as a backupmv ~/.kube/config ~/.kube/config-bkp
# 2. Download the new cluster config into .kube/# (e.g. tkb-kubeconfig.yaml from your cloud provider)
# 3. Set KUBECONFIG to point at both filesexport KUBECONFIG=~/.kube/config-bkp:~/.kube/tkb-kubeconfig.yaml
# 4. Flatten into a single merged filekubectl config view --flatten > ~/.kube/config
# 5. Switch the env var to the new unified fileexport KUBECONFIG=~/.kube/configkubectl Syntax
Section titled “kubectl Syntax”Every kubectl command follows the same pattern:
kubectl [command] [TYPE] [NAME] [flags]| Part | Description | Examples |
|---|---|---|
| command | The action to perform | get, create, apply, delete, describe, edit, patch, exec, logs |
| TYPE | Resource type - full name or abbreviation | pods/po, services/svc, deployments/deploy, nodes/no |
| NAME | Object name (metadata.name) | my-pod, frontend |
| flags | Optional parameters | -n namespace, -o yaml, --watch |
Namespace Flags
Section titled “Namespace Flags”Most commands operate on the current namespace by default. Use these flags to control scope:
| Flag | Meaning |
|---|---|
-n <name> / --namespace=<name> | Target a specific namespace |
-A / --all-namespaces | Query across all namespaces |
Set a persistent default with kubectl config set-context --current --namespace=<name> to avoid repeating -n on every command.
Output Formats
Section titled “Output Formats”Control what kubectl prints with the -o flag:
| Flag | Output | Best used for |
|---|---|---|
-o wide | Extra columns (node, IP, etc.) | Quick inspection at the terminal |
-o yaml | Full object as YAML | Copying a live object’s spec into a manifest |
-o json | Full object as JSON | Programmatic processing |
-o jsonpath='{.spec.nodeName}' | Extracted field value | Scripting and automation |
-o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName | Custom table | Tailored human-readable output |
-o name | Just type/name | Piping into kubectl delete or scripts |
Essential Commands
Section titled “Essential Commands”# --- Inspecting resources ---kubectl get pods # list all pods in current namespacekubectl get pods -n kube-system # specific namespacekubectl get pods -A # all namespaceskubectl get pods -o wide # extra columns (node, IP)kubectl get pods -o yaml # full YAML outputkubectl get pods --watch # stream live updates
kubectl describe pod <name> # detailed view + eventskubectl get events --field-selector type=Warning # warnings only
# --- Logs ---kubectl logs <pod-name> # container stdout/stderrkubectl logs <pod-name> -c <container> # specific container in a multi-container podkubectl logs <pod-name> --previous # logs from last (crashed) containerkubectl logs <pod-name> -f # follow/stream logs
# --- Exec and copy ---kubectl exec -it <pod-name> -- bash # interactive shellkubectl exec <pod-name> -- <command> # one-shot commandkubectl cp <pod-name>:/path/to/file ./local # copy file from pod to localkubectl cp ./local <pod-name>:/path/to/file # copy file from local to pod
# --- Port forwarding ---kubectl port-forward pod/<name> 8080:80 # forward local port to podkubectl port-forward svc/<name> 8080:80 # forward local port to serviceListing API Resources
Section titled “Listing API Resources”kubectl api-resources # all resource types with short names, groups, and scopekubectl api-versions # all enabled API versionskubectl explain pods # field-level documentation for Podskubectl explain pods.spec.containers # drill into nested fieldskubectl explain deployment.spec.strategy.rollingUpdateObject Management Strategies
Section titled “Object Management Strategies”Kubernetes supports three approaches for creating and managing objects. Kubernetes objects (Pods, Deployments, Services, and more) are covered in Kubernetes API & Object Model.
A - Imperative Object Management
Section titled “A - Imperative Object Management”Direct kubectl commands manage objects without a manifest file. Fastest for one-off tasks and quick iteration.
Creating:
kubectl run frontend --image=nginx # create a Podkubectl create deployment app --image=nginx # create a Deploymentkubectl create service clusterip my-svc --tcp=80:80kubectl create configmap app-config --from-literal=ENV=prodkubectl create secret generic db-secret --from-literal=password=s3cr3tUpdating:
kubectl edit deployment app # opens live config in editor; saves on exitkubectl patch pod my-pod -p '{"spec":{"containers":[{"name":"nginx","image":"nginx:1.25"}]}}'kubectl set image deployment/app nginx=nginx:1.25kubectl scale deployment app --replicas=5Deleting:
kubectl delete pod my-podkubectl delete pod my-pod --now # skip 30-second grace period (SIGKILL immediately)kubectl delete deployment app # deletes the Deployment and its PodsB - Declarative Object Management
Section titled “B - Declarative Object Management”YAML or JSON manifest files declare the desired state. The recommended approach for production, version control, and GitOps.
kubectl apply -f pod.yaml # create or update from a filekubectl apply -f ./manifests/ # apply all files in a directorykubectl apply -f https://example.com/app.yaml # apply from a URLkubectl delete -f pod.yaml # delete objects described in a fileWhy apply instead of create:
applyis idempotent - it compares the file with the live state and applies only the diffapplystores a JSON snapshot in the annotationkubectl.kubernetes.io/last-applied-configurationto track historical changescreatefails if the resource already exists;applysucceeds whether creating or updating
C - The Hybrid Approach (Dry-Run)
Section titled “C - The Hybrid Approach (Dry-Run)”Not every configuration is available as a flag. The hybrid approach uses imperative commands to generate boilerplate YAML without deploying anything - then you edit the file and apply it declaratively.
# Generate a Pod manifest without creating the Podkubectl run frontend --image=nginx -o yaml --dry-run=client > pod.yaml
# Generate a Deployment manifestkubectl create deployment app --image=nginx -o yaml --dry-run=client > deploy.yaml
# Generate a Service manifestkubectl create service clusterip my-svc --tcp=80:80 -o yaml --dry-run=client > svc.yamlThen edit the generated YAML and deploy:
kubectl apply -f pod.yamlRollouts
Section titled “Rollouts”Kubernetes tracks Deployment changes as revisions, enabling you to monitor progress and roll back if something goes wrong.
# Monitor a rollout as it progresseskubectl rollout status deployment/app
# View revision historykubectl rollout history deployment/app
# Show the exact changes in a specific revisionkubectl rollout history deployment/app --revision=2
# Roll back to the previous revisionkubectl rollout undo deployment/app
# Roll back to a specific revisionkubectl rollout undo deployment/app --to-revision=1
# Pause and resume a rollout (useful for canary testing)kubectl rollout pause deployment/appkubectl rollout resume deployment/app
# Restart all pods in a deployment (triggers a rolling replacement)kubectl rollout restart deployment/appExposing and Scaling Applications
Section titled “Exposing and Scaling Applications”Exposing a Deployment
Section titled “Exposing a Deployment”# Create a Service to expose a Deploymentkubectl expose deployment app --port=80 --target-port=8080
# LoadBalancer Service (cloud environments - provisions a public IP)kubectl expose deployment app --type=LoadBalancer --port=80
# NodePort (local/no-cloud environments - opens a port on every node)kubectl expose deployment app --type=NodePort --port=80In cloud environments, LoadBalancer Services automatically provision a public-facing load balancer. In local clusters without a cloud controller, Kubernetes falls back to NodePort - a port opened on every worker node that forwards traffic to the Service.
Scaling
Section titled “Scaling”kubectl scale deployment app --replicas=10kubectl autoscale deployment app --min=2 --max=10 --cpu-percent=80When scaled, the Service automatically acts as an internal load balancer - distributing incoming requests across all available Pod replicas.
GitOps and Real-World Practices
Section titled “GitOps and Real-World Practices”In production environments, teams strongly favour the declarative approach combined with GitOps principles:
- Declarative YAML manifests are stored in a Git repository, which becomes the single source of truth for the cluster’s desired state
- Tools like Argo CD and Flux watch the Git repository and automatically sync changes to the cluster
- Every change to cluster state is a Git commit - giving you a full, auditable history and trivial rollbacks (
git revert) - Drift detection ensures the live cluster never silently diverges from what is in Git
GitOps treats the cluster as a read-only artefact of the repository, not as a system that is manually configured.