Imperative commands with kubectl

Imperative commands with kubectl

Master the tool of the trade. Learn to navigate your cluster at the speed of thought, debug in real-time, and prototype new services without touching a single YAML file.

Imperative Commands with kubectl: The Developer's Survival Guide

In the previous lesson, we talked about the "Grown-up" way to manage Kubernetes: Declarative YAML. This is what you use for 99% of your production work. But what about the other 1%? What about when you are in the middle of a massive outage at 2:00 AM and you need to see a pod's logs right now? Or when you want to quickly test if a new Docker image even boots before you spend 30 minutes writing its Deployment manifest?

This is where Imperative Commands and the kubectl CLI shine.

kubectl is a powerhouse tool. It is your eyes, your ears, and your hands inside the cluster. In this lesson, we will go beyond get pods and get nodes. We will learn the "Ninja" tricks for rapid prototyping, real-time debugging, and live manipulation of cluster resources. We will build a "Cheat Sheet" of commands that every professional engineer needs to have memorized.


1. What is kubectl? (The CLI Engine)

kubectl is a command-line client that speaks to the Kubernetes API Server (The Brain).

When you run a command like kubectl get pods, the CLI performs the following steps:

  1. Reads Config: It looks at your ~/.kube/config file to find the cluster's address and your authentication token.
  2. Wraps Request: It converts your human-readable command into a RESTful API call (e.g., GET /api/v1/namespaces/default/pods).
  3. Executes: It sends the request via HTTPS, receives a JSON response, and prettifies it for your terminal.

2. Rapid Prototyping: The "kubectl run" Command

Sometimes you just want to run a container now. You don't want to create a deployment, a service, and a secret. You just want a shell.

Creating a temporary pod:

# Start a Python pod and get a terminal inside it immediately
kubectl run test-python --image=python:3.11-slim --rm -it -- /bin/bash
  • --rm: Deletes the pod when you exit (keeps your cluster clean!).
  • -it: Interactive terminal.
  • --image: Which Docker image to use.

Creating a full Deployment imperatively:

While not recommended for production, this is great for testing:

kubectl create deployment my-api --image=myrepo/api:v1 --replicas=3

3. The "Big Three" of Debugging

When a Pod is marked as "Failed" or "Pending," or is "Running" but your API is returning a 500 error, there is a specific workflow you should follow.

A. Describe: The "What happened?" Command

kubectl describe pod <name> is the most important debugging tool. It doesn't show application logs; it shows Cluster Events.

  • Look for: "FailedScheduling" (Cluster is full), "PullImageError" (Wrong image name), or "Back-off restarting failed container."

B. Logs: The "What is the app saying?" Command

If the cluster thinks the pod is fine but the app is broken, you need the standard output.

# Stream the logs (like tail -f)
kubectl logs <pod-name> -f

# If the pod has multiple containers (Sidecars), specify which one
kubectl logs <pod-name> -c main-container

# See why a pod crashed in the past (The previous instance)
kubectl logs <pod-name> --previous

C. Exec: The "Let me see for myself" Command

Sometimes you need to verify if a file exists or if the database is reachable from the pod.

kubectl exec -it <pod-name> -- bash
# Once inside, you can run 'curl', 'env', or 'ls'

4. Live Editing and Scaling

You can change the cluster state on the fly without updating your local YAML files.

Scaling up/down manually:

kubectl scale deployment/ai-engine --replicas=10

Direct Editing (The "Vim" for K8s):

This command opens the live YAML of a resource in your terminal's text editor.

kubectl edit deployment/ai-engine
# Save and exit to apply the change immediately to the live cluster.

Warning: Never do this in production! Your Git repository will be out of sync with reality. This is for dev/test only.


5. Navigating with Labels and Selectors

As your cluster grows to 500 pods, finding the right one is like finding a needle in a haystack.

Filter by Labels:

# Get all pods for the 'billing' team
kubectl get pods -l team=billing

# Get pods for 'billing' that are in 'production'
kubectl get pods -l team=billing,env=prod

Custom Columns (The "Pro" View):

Stop scrolling through massive tables. Pick exactly what you want to see.

kubectl get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP,NODE:.spec.nodeName

6. Practical Scenario: Debugging a Python AI Agent

Imagine your FastAPI agent is failing to connect to AWS Bedrock.

  1. Check Status: kubectl get pods. It says CrashLoopBackOff.
  2. Investigate: kubectl describe pod <name>. You see Exit Code 1.
  3. Check Logs: kubectl logs <name>. You see botocore.exceptions.NoCredentialsError.
  4. Live Test: kubectl exec -it <name> -- env | grep AWS. You realize the AWS_REGION variable is missing.
  5. Temporary Fix: kubectl set env deployment/ai-agent AWS_REGION=us-east-1.
  6. Verify: Pod restarts and logs now show successful connection.
  7. Final Step: Update your Declarative YAML (Module 3) to include this variable permanently.

7. AI Implementation: Real-time Metric Watching

When you are load-testing a new LangChain workflow, you want to see how much CPU it consumes in real-time.

You can use kubectl top. (Requires the Metrics Server to be installed).

# See which pods are eating the most RAM
kubectl top pods --sort-by=memory

# See which node is the most stressed
kubectl top nodes

This is invaluable for deciding what your Resource Limits (Lesson 4) should be for a production deployment.


8. Summary and Key Takeaways

  • kubectl is your primary interface to the API.
  • Run & Create: Use for rapid testing and prototyping.
  • Describe & Logs: The dynamic duo of troubleshooting.
  • Exec: Your internal shell into the containerized world.
  • Labels: Use them to filter and navigate complex clusters.
  • Top: Monitor real-time resource usage.

In the next lesson, we will move back to the "Management" side and explore the operations of Rolling updates and rollbacks.


9. SEO Metadata & Keywords

Focus Keywords: kubectl cheat sheet for developers, K8s imperative commands tutorial, debugging Kubernetes pods with kubectl, kubectl exec vs run, filter kubectl by labels, real-time K8s monitoring with kubectl top.

Meta Description: Master the Kubernetes command-line interface. Learn the essential imperative commands for rapid prototyping, real-time debugging, and live cluster management. Build your survival guide for the most powerful CLI in the cloud-native world.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn