PART 1: CORE THEORY
1. kubectl Architecture
kubectl is the command-line interface for Kubernetes. It's a client that talks to the kube-apiserver via REST.
The Request Flow
text
┌─────────────────────────────────────────────────────────────┐
│ kubectl REQUEST FLOW │
│ │
│ kubectl get pods │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Read kubeconfig │ (auth, cluster, context) │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Build HTTP │ (GET /api/v1/namespaces/default/pods) │
│ │ Request │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Send to API │ (TLS, auth token, etc.) │
│ │ Server │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Receive JSON │ │
│ │ Response │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Format for │ (table, yaml, json, etc.) │
│ │ Terminal │ │
│ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Key Facts
| Fact | Detail |
| Language | Go |
| Protocol | REST (HTTP/HTTPS) |
| Authentication | From kubeconfig (certs, tokens, exec plugins) |
| Authorization | API server enforces RBAC |
| Config location | ~/.kube/config (default) |
| Env overrides | KUBECONFIG, KUBECTL_CONTEXT, KUBECTL_NAMESPACE |
What kubectl Is Not
- Not a control plane component. You can delete kubectl; the cluster keeps running.
- Not a proxy. It's a direct client to the API server.
- Not declarative by itself. Declarative behavior comes from
kubectl apply+ server-side reconciliation.
kubectl Version
bash
kubectl version --client # Client version
kubectl version # Client + server versions
kubectl version --short # Compact output
# Best practice: client version within ±1 minor of server
Version skew policy: kubectl supports one minor version of skew (older or newer) relative to the API server.
2. kubeconfig and Contexts
kubeconfig is a YAML file that tells kubectl:
- Which cluster to talk to
- How to authenticate
- Which namespace to use
The kubeconfig Structure
yaml
apiVersion: v1
kind: Config
clusters:
- name: dev
cluster:
server: https://dev.k8s.example.com:6443
certificate-authority-data: <base64>
- name: prod
cluster:
server: https://prod.k8s.example.com:6443
certificate-authority-data: <base64>
users:
- name: alice
user:
client-certificate-data: <base64>
client-key-data: <base64>
- name: alice-prod
user:
token: <token>
contexts:
- name: dev
context:
cluster: dev
user: alice
namespace: default
- name: prod
context:
cluster: prod
user: alice-prod
namespace: default
current-context: dev
The Three Sections
| Section | Purpose |
| clusters | API server URLs and CA certs |
| users | Credentials (certs, tokens, exec plugins) |
| contexts | Combinations of cluster + user + namespace |
Managing Contexts
bash
# List contexts
kubectl config get-contexts
# Current context
kubectl config current-context
# Switch context
kubectl config use-context prod
# Rename
kubectl config rename-context old-name new-name
# Set default namespace for current context
kubectl config set-context --current --namespace=dev
# Delete a context
kubectl config delete-context prod
# View raw config
kubectl config view
kubectl config view --minify # Only current context
kubectl config view --raw # Show secrets
Multiple kubeconfig Files
bash
# Set via environment variable
export KUBECONFIG=~/.kube/config:~/.kube/config-prod
# Merge into a single file
KUBECONFIG=~/.kube/config:~/.kube/config-prod kubectl config view --flatten > ~/.kube/merged
# Use a specific file
kubectl --kubeconfig=/path/to/config get pods
Authentication Methods
| Method | Where Used |
| Client certificates | Self-managed clusters |
| Bearer tokens | ServiceAccounts, CI |
| Exec plugins | AWS (aws eks get-token), GCP, Azure |
| OIDC | Enterprise SSO |
| Basic auth | Legacy (deprecated) |
| Webhook | Custom auth |
Exec plugin example (AWS EKS):
yaml
users:
- name: arn:aws:eks:us-east-1:123456789:cluster/prod
user:
exec:
apiVersion: client.authentication.k8s.io/v1beta1
command: aws
args:
- eks
- get-token
- --cluster-name
- prod
The exec plugin runs a command that outputs a token. Tokens expire and are refreshed automatically.
Dangerous Patterns
| Pattern | Risk |
| Sharing kubeconfig files | Auditing becomes impossible |
| Committing kubeconfig to Git | Leaks credentials |
Using admin context for daily work | Too much privilege |
| Skipping context check | Running prod command in dev cluster |
Production tip: Add cluster name to your shell prompt or use kubectx/kubens for safety.
3. Imperative vs Declarative
Kubernetes supports two ways to manage resources. Knowing when to use each is a skill.
Imperative Commands
Direct actions:
bash
kubectl run nginx --image=nginx:1.25-alpine
kubectl create deployment web --image=nginx --replicas=3
kubectl expose deployment web --port=80
kubectl scale deployment web --replicas=5
kubectl delete pod nginx
kubectl set image deployment/web nginx=nginx:1.26-alpine
kubectl label pod nginx env=prod
kubectl annotate pod nginx owner=alice
Pros: Fast, one-liners, no YAML files needed.
Cons: Not reproducible, no version control, hard to review.
Declarative Commands
Apply from manifests:
bash
kubectl apply -f deployment.yaml
kubectl apply -f ./manifests/
kubectl apply -k ./kustomize/
Pros: Reproducible, version-controlled, peer-reviewable, works with GitOps.
Cons: Requires YAML files, more setup.
The Spectrum
There are actually four levels:
| Level | Example | Use Case |
| Pure imperative | kubectl run nginx --image=nginx | Quick tests, debugging |
| Imperative with output | kubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yaml | Generating manifests |
| Declarative apply | kubectl apply -f web.yaml | Standard workflow |
| GitOps | Argo CD / Flux watches Git | Production standard |
The Best Practice
Use imperative for:
- Quick tests and experiments
- Debugging (creating test pods)
- Learning
- Generating YAML templates
Use declarative for:
- Everything else
- Anything that will persist
- Anything that will be reviewed
- Anything in production
The Magic of --dry-run=client -o yaml
The most powerful pattern:
bash
kubectl create deployment web \
--image=nginx:1.25-alpine \
--replicas=3 \
--dry-run=client \
-o yaml > web.yaml
This generates a clean YAML manifest from an imperative command — perfect for starting a declarative workflow.
Comparing Output
| Command | What It Does |
--dry-run=client | Only validates client-side, doesn't send to server |
--dry-run=server | Sends to server, validates server-side (admission, etc.) |
-o yaml | Outputs as YAML |
-o json | Outputs as JSON |
4. The Core Command Set
Five commands cover 80% of daily work.
kubectl get
Retrieves resources.
bash
# Basic
kubectl get pods
kubectl get deployments
kubectl get services
kubectl get nodes
kubectl get all # All common resources in current namespace
kubectl get all -A # All namespaces
# Wide output
kubectl get pods -o wide # Show node, IP, etc.
# By name
kubectl get pod nginx-abc123
# Specific namespaces
kubectl get pods -n prod
kubectl get pods --all-namespaces
# Watch (live)
kubectl get pods -w
# Sort
kubectl get pods --sort-by=.metadata.creationTimestamp
# Show labels
kubectl get pods --show-labels
# Filter by label
kubectl get pods -l app=nginx
kubectl get pods -l 'environment in (prod,staging)'
# Filter by field
kubectl get pods --field-selector status.phase=Running
kubectl get pods --field-selector spec.nodeName=node-1
kubectl describe
Detailed human-readable info, plus events.
bash
kubectl describe pod nginx-abc123
kubectl describe deployment web
kubectl describe node node-1
kubectl describe svc nginx
The value of describe: It shows Events at the bottom — the single best debugging resource.
kubectl logs
Retrieves container logs.
bash
# Basic
kubectl logs nginx-abc123
# Follow (live)
kubectl logs -f nginx-abc123
# Previous container instance
kubectl logs nginx-abc123 --previous
# Recent only
kubectl logs nginx-abc123 --tail=100
kubectl logs nginx-abc123 --since=1h
kubectl logs nginx-abc123 --since-time="2024-01-15T10:00:00Z"
# Specific container (multi-container Pod)
kubectl logs nginx-abc123 -c sidecar
# All containers
kubectl logs nginx-abc123 --all-containers
# Prefix with Pod name
kubectl logs nginx-abc123 --prefix
# Logs from all Pods matching label
kubectl logs -l app=nginx --tail=50
# Time stamps
kubectl logs nginx-abc123 --timestamps
Tip: kubectl logs -f -l app=nginx is often easier than exec-ing into individual Pods.
kubectl exec
Runs commands inside containers.
bash
# Interactive shell
kubectl exec -it nginx-abc123 -- /bin/sh
kubectl exec -it nginx-abc123 -- bash
# Single command
kubectl exec nginx-abc123 -- cat /etc/nginx/nginx.conf
kubectl exec nginx-abc123 -- env
kubectl exec nginx-abc123 -- ps aux
# Specific container
kubectl exec -it nginx-abc123 -c sidecar -- /bin/sh
# Multiple commands
kubectl exec nginx-abc123 -- sh -c "cd /app && ls -la"
kubectl delete
Removes resources.
bash
# By name
kubectl delete pod nginx-abc123
kubectl delete deployment web
kubectl delete svc nginx
# By file
kubectl delete -f deployment.yaml
# By label
kubectl delete pods -l app=nginx
# By selector
kubectl delete pods --field-selector status.phase=Failed
# Force (immediate)
kubectl delete pod nginx-abc123 --force --grace-period=0
# All in namespace
kubectl delete all --all
The Other 15% Most-Used Commands
| Command | Purpose |
kubectl apply | Apply manifests |
kubectl create | Create from imperative |
kubectl edit | Edit live resource |
kubectl patch | Partial update |
kubectl scale | Scale replicas |
kubectl set image | Update image |
kubectl rollout | Manage rollouts |
kubectl port-forward | Local port forward |
kubectl cp | Copy files |
kubectl top | Resource usage |
kubectl auth can-i | Check permissions |
kubectl explain | Built-in docs |
kubectl api-resources | Available resource types |
kubectl api-versions | Available API versions |
kubectl cluster-info | Cluster endpoint info |
5. kubectl apply vs create vs replace
This is where declarative Kubernetes gets subtle.
The Three Commands
| Command | Behavior |
| kubectl create | Create resource; fail if exists |
| kubectl replace | Replace resource entirely; must exist |
| kubectl apply | Create or update; uses 3-way merge |
The 3-Way Merge
kubectl apply compares three things:
- Last applied configuration (stored in
kubectl.kubernetes.io/last-applied-configurationannotation) - New configuration (what you're applying now)
- Live configuration (what's currently in etcd)
The result is a merge that preserves fields not in your manifest.
Example:
Original apply:
yaml
spec:
replicas: 3
template:
spec:
containers:
- name: web
image: nginx:1.24
Then someone runs kubectl edit and changes replicas to 5.
Then you re-apply with replicas: 3.
Result: replicas goes back to 3 (your manifest is source of truth). If you had removed replicas from the manifest entirely, the 5 would be preserved.
Why This Matters
| Action | Behavior |
| Field in manifest | Managed by apply |
| Field removed from manifest | Apply removes it (via 3-way merge) |
| Field added externally | Preserved unless you explicitly remove |
Server-Side Apply (SSA)
The modern alternative:
bash
kubectl apply --server-side -f deployment.yaml
Key differences:
| Aspect | Client-Side Apply | Server-Side Apply |
| Merge location | kubectl | API server |
| State storage | last-applied-configuration annotation | managedFields |
| Conflict handling | Whole-resource | Field-level |
| Multiple controllers | Hard | Easy |
| Performance | Slower (client does work) | Faster |
Server-side apply is the future. Used by Flux, Argo CD, and most modern tooling.
When to Use Which
| Scenario | Command |
| Initial creation, one-off | kubectl create |
| Complete replacement | kubectl replace (rare) |
| Day-to-day declarative | kubectl apply (client or server) |
| Multiple controllers | kubectl apply --server-side |
| CI/CD | kubectl apply --server-side or GitOps |
The Removal Trap
If you apply a manifest that removes a field, Kubernetes will remove it. But if you use create, you can't re-apply without deleting first.
Best practice: Always apply, never create (except for generating manifests).
1:1 copy of the class Google Doc, code in code blocks.