Stage 2, Part 1 of 9 · p. 10, kubectl Mastery & Debugging

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

FactDetail
LanguageGo
ProtocolREST (HTTP/HTTPS)
AuthenticationFrom kubeconfig (certs, tokens, exec plugins)
AuthorizationAPI server enforces RBAC
Config location~/.kube/config (default)
Env overridesKUBECONFIG, KUBECTL_CONTEXT, KUBECTL_NAMESPACE

What kubectl Is Not

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:

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

SectionPurpose
clustersAPI server URLs and CA certs
usersCredentials (certs, tokens, exec plugins)
contextsCombinations 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

MethodWhere Used
Client certificatesSelf-managed clusters
Bearer tokensServiceAccounts, CI
Exec pluginsAWS (aws eks get-token), GCP, Azure
OIDCEnterprise SSO
Basic authLegacy (deprecated)
WebhookCustom 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

PatternRisk
Sharing kubeconfig filesAuditing becomes impossible
Committing kubeconfig to GitLeaks credentials
Using admin context for daily workToo much privilege
Skipping context checkRunning 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:

LevelExampleUse Case
Pure imperativekubectl run nginx --image=nginxQuick tests, debugging
Imperative with outputkubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yamlGenerating manifests
Declarative applykubectl apply -f web.yamlStandard workflow
GitOpsArgo CD / Flux watches GitProduction standard

The Best Practice

Use imperative for:

Use declarative for:

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

CommandWhat It Does
--dry-run=clientOnly validates client-side, doesn't send to server
--dry-run=serverSends to server, validates server-side (admission, etc.)
-o yamlOutputs as YAML
-o jsonOutputs 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

CommandPurpose
kubectl applyApply manifests
kubectl createCreate from imperative
kubectl editEdit live resource
kubectl patchPartial update
kubectl scaleScale replicas
kubectl set imageUpdate image
kubectl rolloutManage rollouts
kubectl port-forwardLocal port forward
kubectl cpCopy files
kubectl topResource usage
kubectl auth can-iCheck permissions
kubectl explainBuilt-in docs
kubectl api-resourcesAvailable resource types
kubectl api-versionsAvailable API versions
kubectl cluster-infoCluster endpoint info

5. kubectl apply vs create vs replace

This is where declarative Kubernetes gets subtle.

The Three Commands

CommandBehavior
kubectl createCreate resource; fail if exists
kubectl replaceReplace resource entirely; must exist
kubectl applyCreate or update; uses 3-way merge

The 3-Way Merge

kubectl apply compares three things:

  1. Last applied configuration (stored in kubectl.kubernetes.io/last-applied-configuration annotation)
  2. New configuration (what you're applying now)
  3. 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

ActionBehavior
Field in manifestManaged by apply
Field removed from manifestApply removes it (via 3-way merge)
Field added externallyPreserved unless you explicitly remove

Server-Side Apply (SSA)

The modern alternative:

bash
kubectl apply --server-side -f deployment.yaml

Key differences:

AspectClient-Side ApplyServer-Side Apply
Merge locationkubectlAPI server
State storagelast-applied-configuration annotationmanagedFields
Conflict handlingWhole-resourceField-level
Multiple controllersHardEasy
PerformanceSlower (client does work)Faster

Server-side apply is the future. Used by Flux, Argo CD, and most modern tooling.

When to Use Which

ScenarioCommand
Initial creation, one-offkubectl create
Complete replacementkubectl replace (rare)
Day-to-day declarativekubectl apply (client or server)
Multiple controllerskubectl apply --server-side
CI/CDkubectl 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.