TExcelTAD
Home › Kubernetes › kubectl Basics

kubectl Basics

kubectl (pronounced "cube-control" or "cube-C-T-L") is the command-line client for the Kubernetes API. Almost every command follows the same shape:

text
kubectl <verb> <resource-type> [name] [flags]
Verb What it does Example
get List objects in a table kubectl get pods
describe Detailed, human-readable view incl. events kubectl describe pod web-0
apply Create or update from a manifest (declarative) kubectl apply -f app.yaml
create Create (fails if it exists) kubectl create namespace dev
delete Delete objects kubectl delete -f app.yaml
logs Container logs kubectl logs web-0 -f
exec Run a command in a container kubectl exec -it web-0 -- sh
port-forward Tunnel a local port to a Pod/Service kubectl port-forward svc/web 8080:80
explain Built-in documentation for fields kubectl explain pod.spec.containers
edit Open the live object in your editor kubectl edit deploy web

Resource types and short names

Resource types can be singular, plural or abbreviated: pod, pods and po all mean the same.

bash
kubectl api-resources | head

Sample output:

text
NAME                     SHORTNAMES   APIVERSION   NAMESPACED   KIND
configmaps               cm           v1           true         ConfigMap
endpoints                ep           v1           true         Endpoints
events                   ev           v1           true         Event
namespaces               ns           v1           false        Namespace
nodes                    no           v1           false        Node
persistentvolumeclaims   pvc          v1           true         PersistentVolumeClaim
persistentvolumes        pv           v1           false        PersistentVolume
pods                     po           v1           true         Pod
services                 svc          v1           true         Service

kubectl resolves what you type against this table. A model of that lookup:

python · try it yourself
RESOURCES = [
    ("pods", "po", "Pod"),
    ("services", "svc", "Service"),
    ("deployments", "deploy", "Deployment"),
    ("configmaps", "cm", "ConfigMap"),
    ("namespaces", "ns", "Namespace"),
    ("persistentvolumeclaims", "pvc", "PersistentVolumeClaim"),
]

def resolve(word):
    w = word.lower()
    for plural, short, kind in RESOURCES:
        if w in (plural, short, kind.lower()):
            return kind
    return f'error: the server doesn\'t have a resource type "{word}"'

for typed in ["po", "Pod", "svc", "deployments", "cm", "pvc", "pdos"]:
    print(f"{typed:12} -> {resolve(typed)}")
po           -> Pod
Pod          -> Pod
svc          -> Service
deployments  -> Deployment
cm           -> ConfigMap
pvc          -> PersistentVolumeClaim
pdos         -> error: the server doesn't have a resource type "pdos"

Imperative vs declarative

You can manage objects in two styles:

bash
# Imperative: commands describe actions
kubectl create deployment web --image=nginx:1.27 --replicas=2
kubectl scale deployment web --replicas=4
kubectl set image deployment/web nginx=nginx:1.28

# Declarative: files describe state; apply makes it so
kubectl apply -f web.yaml
kubectl diff -f web.yaml     # preview what apply would change

Imperative commands are great for experiments. For anything that matters, use declarative files kept in Git: they are reviewable, repeatable and are the basis of GitOps.

Tip: Generate a starting manifest instead of typing it from memory: kubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yaml

Output formats

-o changes how get prints objects:

Flag Output
(none) Short table
-o wide Table with extra columns (node, IP)
-o yaml / -o json The full object, including status
-o name pod/web-0 style names, handy in scripts
-o jsonpath='{.items[*].metadata.name}' Pick fields with a JSONPath expression
-o custom-columns=NAME:.metadata.name,IP:.status.podIP Your own table

The default table is produced from fields of each object. This model builds the kubectl get pods table from a list of Pod objects, including the READY column (ready containers / total):

python · try it yourself
pods = [
    {"name": "web-7c5d-4xk2p", "phase": "Running", "containers": [True, True], "restarts": 0},
    {"name": "web-7c5d-9qmzt", "phase": "Running", "containers": [True, False], "restarts": 3},
    {"name": "batch-x81kq", "phase": "Pending", "containers": [False], "restarts": 0},
]

rows = [("NAME", "READY", "STATUS", "RESTARTS")]
for p in pods:
    ready = f"{sum(p['containers'])}/{len(p['containers'])}"
    rows.append((p["name"], ready, p["phase"], str(p["restarts"])))

widths = [max(len(r[i]) for r in rows) for i in range(4)]
for r in rows:
    print("   ".join(cell.ljust(w) for cell, w in zip(r, widths)).rstrip())
NAME             READY   STATUS    RESTARTS
web-7c5d-4xk2p   2/2     Running   0
web-7c5d-9qmzt   1/2     Running   3
batch-x81kq      0/1     Pending   0

Useful everyday flags

Flag Meaning
-n dev / --namespace dev Work in namespace dev
-A / --all-namespaces List across all namespaces
-l app=web Filter by label selector
-w Watch: keep printing changes
--sort-by=.metadata.creationTimestamp Sort the table
--dry-run=client -o yaml Print what would be sent, change nothing

JSONPath picks fields out of the JSON form of an object. Python's dictionaries make the same idea easy to see: {.items[*].metadata.name} means "for every item, take metadata.name":

python · try it yourself
import json

response = json.loads("""
{"kind": "PodList", "items": [
  {"metadata": {"name": "web-1", "labels": {"app": "web"}}, "status": {"podIP": "10.244.1.5"}},
  {"metadata": {"name": "web-2", "labels": {"app": "web"}}, "status": {"podIP": "10.244.2.7"}},
  {"metadata": {"name": "db-0", "labels": {"app": "db"}}, "status": {"podIP": "10.244.1.9"}}
]}
""")

# kubectl get pods -o jsonpath='{.items[*].metadata.name}'
print(" ".join(item["metadata"]["name"] for item in response["items"]))

# kubectl get pods -l app=web -o custom-columns=NAME:.metadata.name,IP:.status.podIP
print(f"{'NAME':8}{'IP'}")
for item in response["items"]:
    if item["metadata"]["labels"].get("app") == "web":
        print(f"{item['metadata']['name']:8}{item['status']['podIP']}")
web-1 web-2 db-0
NAME    IP
web-1   10.244.1.5
web-2   10.244.2.7

Test yourself

Which command shows a Pod's details together with its recent events?

  1. kubectl get pod web -o name
  2. kubectl describe pod web
  3. kubectl logs web
  4. kubectl explain pod

What does --dry-run=client -o yaml do?

  1. Deletes the object
  2. Prints the manifest that would be sent without changing the cluster
  3. Applies the change twice
  4. Runs the Pod once

Which style is recommended for production changes?

  1. Imperative kubectl edit on the live cluster
  2. Declarative manifests in version control applied with kubectl apply
  3. Editing etcd
  4. SSH into nodes