Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Your first kubectl command

Your first kubectl command — kubernetes tutorial, lesson 5. Learn the foundational command to interact with your cluster, apply it in a hands-on exercise, and connect to the next lesson in the track.

Focus: your first kubectl command

Sponsored

You have a Kubernetes cluster humming along (or a local one via Minikube or Kind), but how do you talk to it? Everything from inspecting Pods to scaling Deployments goes through kubectl, the command-line tool that acts as your cluster's remote control. Without it, you're flying blind. This lesson turns kubectl from a scary incantation into your daily driver—you'll run your first command, understand its anatomy, and gain the confidence to explore further.

The problem this lesson solves

Kubernetes exposes a powerful REST API, but typing raw HTTP requests with curl against the API server is tedious and error-prone. You'd need to manage certificates, tokens, and construct JSON payloads for every action. Worse, you can't see live resource status without polling.

kubectl is the official CLI that wraps this complexity. It authenticates automatically using your kubeconfig file, formats API responses, and supports imperative commands ("do this now") alongside declarative management via YAML files. Without learning kubectl, you cannot:

  • View running Pods or Deployments
  • Debug a crashing container
  • Apply configuration changes from a file
  • Stream logs or port-forward into a service

This lesson gives you the first command that unlocks all of that.

Core concept / mental model

Think of kubectl as a universal remote for your Kubernetes cluster. Every command follows a predictable pattern:

kubectl [action] [resource] [flags]
Part Meaning Example
kubectl The CLI tool
[action] What to do (get, create, delete, describe) get
[resource] What type of Kubernetes object pods
[flags] Optional filters or output format -n default or -o wide

Your first command is kubectl get pods — it lists all Pods in the current namespace. Why start here? Because Pods are the smallest deployable units, and seeing nothing (or something) tells you instantly whether your cluster is alive and you're authenticated.

Pro tip: The kubectl api-resources command shows every resource type your cluster understands — a quick reference when you forget a name.

How it works step by step

  1. Authentication handshake: When you run kubectl, it reads ~/.kube/config (the kubeconfig file). This file contains the cluster's API server URL, your user credentials (certificate or token), and a default namespace. No config, no connection.

  2. API request: kubectl translates your command into an HTTP request to the Kubernetes API server. For example, kubectl get pods becomes a GET /api/v1/namespaces/default/pods request.

  3. Response parsing: The API server returns JSON (often wrapped in a List object). kubectl decodes it and formats the output as a text table by default, or as JSON/YAML with the -o flag.

  4. Local caching: Some get responses can be served from the local kubectl cache (if enabled) for speed, but kubectl describe always hits the live server.

The entire flow happens in sub-second time for small clusters — you see results almost instantly.

Hands-on walkthrough

Prerequisites

  • A running Kubernetes cluster (Minikube, Kind, Docker Desktop, or remote).
  • kubectl installed and configured. Verify with kubectl version --client.
  • A namespace (default is fine) with at least one Pod. Create one quickly with:
kubectl run nginx --image=nginx

Step 1: List Pods

kubectl get pods

Expected output:

NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          12s

Columns explained: - NAME: unique Pod name (auto-generated unless you specify) - READY: 1/1 means one container is running and ready inside the Pod - STATUS: Running, Pending, CrashLoopBackOff, Error, Terminating - RESTARTS: how many times Kubernetes has restarted the Pod (helpful for debugging) - AGE: human-friendly time since creation

Step 2: Get more details with -o wide

kubectl get pods -o wide

This reveals the node the Pod runs on and its internal IP address.

Step 3: Watch for changes

kubectl get pods --watch

The command stays alive and streams new lines when Pods change. Press Ctrl+C to stop.

Step 4: Get all namespaces

kubectl get pods --all-namespaces

List Pods across every namespace — useful for cluster-wide diagnostics.

Your complete first session

# 1. Quick check: cluster reachability
kubectl cluster-info

# 2. List Pods in default namespace
kubectl get pods

# 3. Detailed view of a single Pod
kubectl get pod nginx -o yaml

Pro tip: Pipe -o yaml into a file (kubectl get pod nginx -o yaml > nginx-pod.yaml) for backup or reference.

Compare options / when to choose what

Command Use case Output style
kubectl get pods Quick glance at status Table
kubectl get pods -o wide See node & IP Table with extra columns
kubectl get pods -o yaml Full configuration (debug, backup) YAML
kubectl get pods -o json Programmatic consumption JSON
kubectl describe pod <name> Detailed events & conditions Narrative blocks

For your first command, stick with plain kubectl get pods. It's the least verbose and gives immediate feedback. Move to -o wide when you need node info, and describe when a Pod has errors.

Alternative tools

  • k9s: Terminal UI that shows Pods and other resources with interactive navigation.
  • kubectl plugins (like kubectl-tree) extend functionality.
  • Lens: Desktop app with a rich GUI, but still relies on kubectl under the hood.

But always start with raw kubectl to understand the fundamentals.

Troubleshooting & edge cases

"No resources found in default namespace"

Cause: No Pods exist. kubectl get pods returns empty when a namespace has zero Pods.

Fix: Create one with kubectl run nginx --image=nginx or check another namespace: kubectl get pods -n kube-system.

"The connection to the server was refused"

Cause: kubectl cannot reach the API server. Common reasons: - Cluster is down (Minikube not started). - Wrong context (you're pointing at a different cluster). - Network issue (firewall, VPN).

Fix: kubectl cluster-info should show the server address. Run minikube start if using Minikube, or check your kubeconfig context with kubectl config current-context.

"Unauthorized" or "Forbidden"

Cause: Your kubeconfig contains expired or insufficient credentials.

Fix: Re-authenticate. For Minikube, minikube update-context. For cloud clusters, refresh via gcloud container clusters get-credentials (GKE) or eksctl (EKS).

Missing kubectl command

Install: On macOS brew install kubectl, Linux curl -LO https://dl.k8s.io/release/v1.28.0/bin/linux/amd64/kubectl, Windows choco install kubernetes-cli.

Column or flag not working

kubectl flags are case-sensitive. -o Wide (capital W) fails; use -o wide. Use kubectl options to list global flags.

What you learned & what's next

You now understand the core idea behind kubectl: it's a command-line client that translates simple syntax into API calls. You completed a practical exercise — listing Pods in your cluster — and can troubleshoot common connection and permission errors.

Key takeaways from this lesson: - The universal pattern: kubectl <action> <resource> [flags]. - kubectl get pods is your first command for checking live resources. - Output formats (-o wide, -o yaml, -o json) give progressively more detail. - Authentication is handled by the kubeconfig file at ~/.kube/config. - Edge cases (empty namespace, connection refused, unauthorized) have clear fixes.

Next lesson in this track: Viewing Pod logs with kubectl. You'll extend your command set to read container output — essential for debugging failed Pods. You'll also learn kubectl logs and how to tail them in real-time.

Keep your terminal open; the next lesson assumes you have a running Pod from this one.

Practice recap

Create a new Pod: kubectl run my-app --image=nginx. Then run kubectl get pods -o wide and note the node and IP. Delete it with kubectl delete pod my-app. This reinforces the create/get/delete lifecycle — the most common commands you'll use daily.

Common mistakes

  • Running kubectl get pods before setting the correct namespace — use -n <namespace> or --all-namespaces.
  • Forgetting to install kubectl itself — verify with kubectl version --client.
  • Typing kubectl get pod (singular) instead of kubectl get pods (plural) — works for single resource, but better habit is plural.
  • Overusing --watch without understanding it's interactive and runs until Ctrl+C.

Variations

  1. Use kubectl get all to see Pods, Services, Deployments, etc. at once in a namespace (though it omits some resources).
  2. Replace get with describe for deep-dive details (events, conditions, etc.).
  3. Use kubectl get pods --field-selector=status.phase=Running to filter only running Pods.

Real-world use cases

  • A DevOps engineer checks new deployment health by running kubectl get pods -w during rollout.
  • An SRE debugs a production incident by listing Pods across all namespaces to identify crashes.
  • A developer validates local Minikube setup by running kubectl get nodes and kubectl get pods after starting the cluster.

Key takeaways

  • kubectl get pods is the foundational command for viewing running workloads.
  • The CLI pattern is kubectl [action] [resource] [flags] — learn it to navigate any resource.
  • Output format flags (-o wide, -o yaml, -o json) unlock different levels of detail.
  • Authentication and cluster context come from ~/.kube/config — always verify connectivity first.
  • Empty output doesn't mean broken cluster — check namespace and Pod existence.
  • Start with simple commands and gradually add flags as needed.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.