Common kubectl Commands
Overview
The kubectl command-line utility is the Swiss Army knife of Kubernetes. Before you start creating Pods, Deployments, and Services, you need to master the everyday kubectl commands that work across all Kubernetes objects. This article covers namespaces, contexts, viewing objects, creating and deleting resources, labeling, debugging, and cluster management — everything you need to operate confidently from the terminal.
Prerequisites
- A running Kubernetes cluster (local via
minikube/kind, or a cloud-based cluster) kubectlinstalled and configured on your machine- Basic familiarity with YAML and JSON file formats
- Comfortable using a terminal / command line
Core Concepts
Namespaces
Namespaces are like folders inside your cluster. They organize Kubernetes objects into logical groups. By default, kubectl works with the default namespace. If your team uses separate namespaces for different environments (e.g., dev, staging, production), you can target a specific namespace with the --namespace (or -n) flag.
If you want to see objects across every namespace at once, use the --all-namespaces (or -A) flag.
Contexts
Typing --namespace=mystuff on every command gets tedious. A context saves your preferred namespace (and cluster/user settings) so kubectl remembers them automatically. Contexts are stored in your kubeconfig file, usually located at $HOME/.kube/config.
Think of a context as a bookmark: it remembers which cluster you're talking to, which user credentials to use, and which namespace to default to.
Kubernetes API Objects
Everything in Kubernetes is a RESTful resource (also called a Kubernetes object). Each object lives at a unique HTTP path on the API server. For example, a Pod named my-pod in the default namespace can be found at a URL like /api/v1/namespaces/default/pods/my-pod. When you run kubectl commands, it makes HTTP requests to these URLs behind the scenes.
Declarative vs. Imperative Management
Kubernetes encourages a declarative approach: you describe the desired state in a YAML file and let Kubernetes figure out how to get there. The kubectl apply command is the primary tool for this — it creates objects if they don't exist, and updates them if they do. This is different from imperative commands like kubectl create which only create and will fail if the object already exists.
Labels and Annotations
Labels are key-value pairs attached to objects that are used for identifying and selecting resources. Annotations are also key-value pairs, but they hold non-identifying metadata (e.g., build info, contact details). Both can be added, modified, or removed from the command line.
Cluster Management: Cordon and Drain
Sometimes you need to take a node out of service — for maintenance, repairs, or upgrades. Kubernetes provides two commands for this:
- Cordon — Marks a node as unschedulable. No new Pods will be placed on it, but existing Pods keep running.
- Drain — Evicts all Pods from the node, moving them to other healthy nodes. Use this before physically removing a machine.
After the maintenance is done, you uncordon the node to allow Pods to be scheduled on it again.
Hands-On: Kubernetes Commands
Namespaces
List objects in a specific namespace:
Shorthand version with -n:
List Pods across all namespaces:
Contexts
Create a new context with a custom default namespace:
Switch to the newly created context:
From now on, all kubectl commands will target the mystuff namespace by default — no need to pass -n every time.
Viewing Objects
List all resources of a given type in the current namespace:
Get a specific object by name:
Get more details with wide output:
View the full object definition in YAML:
View the full object definition in JSON:
Remove headers from the output (useful for piping to other commands):
Extract a specific field using JSONPath (e.g., the Pod's IP address):
View multiple object types at once:
Get a detailed, human-readable description of an object:
See the supported fields for a resource type:
Watch an object for live changes:
Creating, Updating, and Deleting Objects
Create or update an object from a YAML file (declarative approach):
Preview what apply would do without making changes:
Edit a live object interactively in your default editor:
View the last applied configuration for an object:
Delete an object using its YAML file:
Delete an object by type and name:
Labeling and Annotating Objects
Add a label to a Pod:
Overwrite an existing label:
Remove a label from a Pod (note the trailing -):
Add an annotation to a Pod:
Debugging Commands
View logs of a running Pod:
View logs of a specific container in a multi-container Pod:
Stream logs continuously (like tail -f):
Open an interactive shell inside a running container:
Attach to the primary process of a running container:
Copy a file from a container to your local machine:
Copy a file from your local machine to a container:
Forward a local port to a Pod (local 8080 → container 80):
Forward a local port to a Service:
View recent cluster events:
Stream cluster events in real time across all namespaces:
View resource usage by nodes:
View resource usage by Pods in the current namespace:
View resource usage by all Pods across every namespace:
Cluster Management
Prevent new Pods from being scheduled on a node:
Evict all Pods from a node (before maintenance):
Re-enable scheduling on a node (after maintenance):
Command Autocompletion
Install bash-completion (choose your OS):
Activate kubectl autocompletion for your current terminal session:
Make it permanent by adding it to your shell profile:
Getting Help
View general kubectl help:
View help for a specific command:
Step-by-Step Example
Let's walk through a realistic workflow: creating an object, inspecting it, labeling it, debugging it, and cleaning up.
- Set up your context so you work in a dedicated namespace:
- Create a simple Pod from a YAML file:
- Assume you have a file called
nginx-pod.yaml:
- Apply it:
- Verify the Pod is running:
- Expected output:
- Add a label to the Pod:
- Inspect the Pod in detail:
- Check the Pod logs:
- Open an interactive shell inside the container:
- Type
exitto leave the shell. - Forward traffic to the Pod and test it locally:
- Open
http://localhost:8080in your browser — you should see the nginx welcome page. PressCtrl+Cto stop forwarding. - Clean up — delete the Pod:
Summary
- Namespaces organize objects into logical groups. Use
-nto target a specific namespace or--all-namespacesto see everything. - Contexts save your default namespace, cluster, and user so you don't have to type them every time.
- Use
kubectl getto list objects,kubectl describefor detailed info, andkubectl explainto explore resource fields. - Use
kubectl apply -fto create or update objects declaratively from YAML files. - Use
kubectl deleteto remove objects — be careful, there is no confirmation prompt. - Use
kubectl labelandkubectl annotateto tag objects with metadata. - For debugging:
kubectl logs,kubectl exec,kubectl port-forward, andkubectl topare your best friends. - For cluster maintenance:
kubectl cordon,kubectl drain, andkubectl uncordonlet you safely take nodes in and out of service. - Enable tab autocompletion to speed up your workflow — it saves a lot of typing.
Further Reading
- kubectl Reference Documentation
- kubectl Cheat Sheet
- Namespaces
- Organizing Cluster Access Using kubeconfig Files
- Debug Applications
Link Interceptor Active