kubectl basics

The commands you will type every day.

Beginner20 min · lesson 5 of 21
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (3 files, 1 KB): kubectl-basics.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/k8s-fund/kubectl-basics.tar.gz && tar -xzf kubectl-basics.tar.gz, which creates ~/lab/kubectl-basics/. SHA-256: 4c0935155ee35264e2ca160397eb0c2c470ccd3d35f3b5b0dac1256f9d9ae1ab

You have already typed apply, get, describe, logs, exec and delete. Most days with Kubernetes use only a few more commands, plus a handful of flags that change what those commands print. Everything here runs against one small Deployment kept in a file.

Contexts: which cluster you talk to

kubectl keeps a list of clusters and credentials in ~/.kube/config. A context is one named pairing of cluster, user and default namespace. Before you change anything, check which context is active:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE * kind-lab kind-lab kind-lab
$ kubectl config current-context
kind-lab

There is one context, kind-lab, which kind wrote when it built the cluster. The * in the CURRENT column marks the active one. The NAMESPACE column is empty, so commands go to the default namespace. At work you may have one context per cluster, and kubectl config use-context NAME switches between them. Deleting something in the wrong cluster is an easy mistake, and this check prevents it.

Create from a file

This file describes a Deployment with two nginx Pods:

web.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels:
app: web
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
ports:
- containerPort: 80
ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl apply -f web.yaml
deployment.apps/web created
$ kubectl rollout status deployment/web
Waiting for deployment "web" rollout to finish: 0 of 2 updated replicas are available... Waiting for deployment "web" rollout to finish: 1 of 2 updated replicas are available... deployment "web" successfully rolled out

kubectl apply -f sends the file to the API server. If the object does not exist it is created, and if it does exist it is updated to match. rollout status waits until the Pods are up.

Choosing what get prints

The output flag -o changes what kubectl get shows:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl get deployments
NAME READY UP-TO-DATE AVAILABLE AGE web 2/2 2 2 1s
$ kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES web-768f9fc75f-7mtwv 1/1 Running 0 2s 10.244.1.2 lab-worker <none> <none> web-768f9fc75f-bkz6n 1/1 Running 0 2s 10.244.2.2 lab-worker2 <none> <none>
$ kubectl get deployment web -o yaml | head -n 25
apiVersion: apps/v1 kind: Deployment metadata: annotations: deployment.kubernetes.io/revision: "1" kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"web"},"name":"web","namespace":"default"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"web"}},"template":{"metadata":{"labels":{"app":"web"}},"spec":{"containers":[{"image":"nginx:1.30.6-alpine","name":"nginx","ports":[{"containerPort":80}]}]}}}} creationTimestamp: "2026-11-11T08:49:19Z" generation: 1 labels: app: web name: web namespace: default resourceVersion: "627" uid: 5156fa14-da40-42f5-9b19-d533fae99312 spec: progressDeadlineSeconds: 600 replicas: 2 revisionHistoryLimit: 10 selector: matchLabels: app: web strategy: rollingUpdate: maxSurge: 25%

Plain get gives a short table. -o wide adds columns such as the Pod IP and the node. -o yaml prints the whole object as the cluster stores it, cut here to its first 25 lines with head. It holds much more than the file you wrote: fields you left out now have defaults (revisionHistoryLimit: 10, maxSurge: 25%), and the cluster added a uid, a creationTimestamp and an annotation holding the last file you applied.

When you want one value, or your own columns, ask for exactly that:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl get deployment web -o jsonpath='{.spec.replicas}{"\n"}'
2
$ kubectl get pods -o custom-columns=POD:.metadata.name,NODE:.spec.nodeName,IMAGE:.spec.containers[0].image
POD NODE IMAGE web-768f9fc75f-7mtwv lab-worker nginx:1.30.6-alpine web-768f9fc75f-bkz6n lab-worker2 nginx:1.30.6-alpine

jsonpath pulls a single field by its path in the YAML, here .spec.replicas, which is handy in scripts. The {"\n"} at the end adds a newline, which jsonpath does not print on its own. custom-columns builds a table from any fields you name, each written as HEADING:path.

Most objects live in a namespace. Without -n, kubectl uses the namespace of the current context, here default:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl get deployments -n kube-system
NAME READY UP-TO-DATE AVAILABLE AGE coredns 1/2 2 1 27s

The coredns Deployment from lesson 2 lives in kube-system. -A instead of -n lists every namespace at once.

Looking closely: describe and explain

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl describe deployment web
Name: web Namespace: default CreationTimestamp: Wed, 11 Nov 2026 08:49:19 +0000 Labels: app=web Annotations: deployment.kubernetes.io/revision: 1 Selector: app=web Replicas: 2 desired | 2 updated | 2 total | 2 available | 0 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 25% max unavailable, 25% max surge ... Conditions: Type Status Reason ---- ------ ------ Available True MinimumReplicasAvailable Progressing True NewReplicaSetAvailable OldReplicaSets: <none> NewReplicaSet: web-768f9fc75f (2/2 replicas created) Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal ScalingReplicaSet 2s deployment-controller Scaled up replica set web-768f9fc75f from 0 to 2

describe is written for people, not scripts. The Replicas line counts desired, updated and available Pods, NewReplicaSet names a related object (lesson 6, Deployments, explains it), and the Events at the end show what happened recently: the Deployment scaled its ReplicaSet from 0 to 2. The Pod template part is cut from this listing.

explain is the built-in reference for every field. The cluster serves it, so it matches the version you run:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl explain deployment.spec.replicas
GROUP: apps KIND: Deployment VERSION: v1 FIELD: replicas <integer> DESCRIPTION: Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.

Commands and files

Commands like kubectl scale or kubectl create deployment are imperative: they tell the cluster to do one thing now. kubectl apply -f is declarative: the file describes the result, and kubectl works out the change. You can mix them, but the file knows nothing about your commands. kubectl diff -f shows how the live object differs from the file:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl scale deployment web --replicas=4 && kubectl get deployment web
deployment.apps/web scaled NAME READY UP-TO-DATE AVAILABLE AGE web 2/4 2 2 3s
$ kubectl diff -f web.yaml
diff -u -N /tmp/LIVE-2823841791/apps.v1.Deployment.default.web /tmp/MERGED-1838500591/apps.v1.Deployment.default.web --- /tmp/LIVE-2823841791/apps.v1.Deployment.default.web 2026-11-11 08:49:22.196008116 +0000 +++ /tmp/MERGED-1838500591/apps.v1.Deployment.default.web 2026-11-11 08:49:22.197008116 +0000 @@ -6,7 +6,7 @@ kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"web"},"name":"web","namespace":"default"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"web"}},"template":{"metadata":{"labels":{"app":"web"}},"spec":{"containers":[{"image":"nginx:1.30.6-alpine","name":"nginx","ports":[{"containerPort":80}]}]}}}} creationTimestamp: "2026-11-11T08:49:19Z" - generation: 2 + generation: 3 labels: app: web name: web @@ -15,7 +15,7 @@ uid: 5156fa14-da40-42f5-9b19-d533fae99312 spec: progressDeadlineSeconds: 600 - replicas: 4 + replicas: 2 revisionHistoryLimit: 10 selector: matchLabels:
$ kubectl apply -f web.yaml && kubectl rollout status deployment/web && kubectl get deployment web
deployment.apps/web configured Waiting for deployment "web" rollout to finish: 2 of 4 updated replicas are available... deployment "web" successfully rolled out NAME READY UP-TO-DATE AVAILABLE AGE web 2/2 2 2 3s

After scale the live Deployment wants 4 Pods, but the file still says 2. In the diff, lines starting with - are the live object and lines with + are what the file would make it: replicas would go from 4 back to 2. The next apply does exactly that. Teams that keep their YAML in Git use apply for this reason: the file stays the truth. Imperative commands are fine for experiments and emergencies, as long as someone updates the file afterwards.

Check a change before applying it

Two habits catch mistakes before they reach the cluster. First change the file, then compare it with the live object:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ sed -i 's/replicas: 2/replicas: 3/' web.yaml && grep replicas web.yaml
replicas: 3
$ kubectl diff -f web.yaml
diff -u -N /tmp/LIVE-2841170187/apps.v1.Deployment.default.web /tmp/MERGED-1587496525/apps.v1.Deployment.default.web --- /tmp/LIVE-2841170187/apps.v1.Deployment.default.web 2026-11-11 08:49:23.018008116 +0000 +++ /tmp/MERGED-1587496525/apps.v1.Deployment.default.web 2026-11-11 08:49:23.018008116 +0000 @@ -6,7 +6,7 @@ kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"web"},"name":"web","namespace":"default"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"web"}},"template":{"metadata":{"labels":{"app":"web"}},"spec":{"containers":[{"image":"nginx:1.30.6-alpine","name":"nginx","ports":[{"containerPort":80}]}]}}}} creationTimestamp: "2026-11-11T08:49:19Z" - generation: 3 + generation: 4 labels: app: web name: web @@ -15,7 +15,7 @@ uid: 5156fa14-da40-42f5-9b19-d533fae99312 spec: progressDeadlineSeconds: 600 - replicas: 2 + replicas: 3 revisionHistoryLimit: 10 selector: matchLabels:
$ kubectl apply -f web.yaml --dry-run=server && kubectl get deployment web
deployment.apps/web configured (server dry run) NAME READY UP-TO-DATE AVAILABLE AGE web 2/2 2 2 4s
$ kubectl apply -f web.yaml && kubectl rollout status deployment/web
deployment.apps/web configured Waiting for deployment "web" rollout to finish: 2 of 3 updated replicas are available... deployment "web" successfully rolled out

The diff shows replicas going from 2 to 3. diff exits with status 1 when it finds a difference, which scripts can use. --dry-run=server sends the change to the API server, which runs every check and then throws the result away: it said configured (server dry run), and the following get still shows two Pods. The real apply then added the third.

There is also --dry-run=client, and the difference matters. This file has a name with capitals and an underscore, which Kubernetes does not allow:

bad.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: Web_App
spec:
replicas: 1
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl apply -f bad.yaml --dry-run=client
deployment.apps/Web_App created (dry run)
$ kubectl apply -f bad.yaml --dry-run=server
The Deployment "Web_App" is invalid: metadata.name: Invalid value: "Web_App": a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')

--dry-run=client never sends the object to the API server for validation, so it reported created (dry run). The server dry run caught the bad name and exited with status 1. Use --dry-run=server when you want to know whether a change would really be accepted.

Delete

This deletes the Deployment the file describes, waits for its Pods to go, and lists what is left. kubectl get all lists the common object types:

ubuntu@secopslog-k8s:~/lab/kubectl-basics · Kubernetes 1.37
$ kubectl delete -f web.yaml && kubectl wait --for=delete pod -l app=web --timeout=90s && kubectl get all
deployment.apps "web" deleted from default namespace pod/web-768f9fc75f-7mtwv condition met pod/web-768f9fc75f-9dtq5 condition met pod/web-768f9fc75f-bkz6n condition met pod/web-768f9fc75f-cwft6 condition met pod/web-768f9fc75f-f8z8w condition met NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 60s

Five Pods reported condition met, including two that were still shutting down after the earlier scale-down from 4 to 2. Only the kubernetes Service is left, which every cluster has in default.

Hands-on

Let kubectl write a Deployment file for you, then use it.

1. Generate the file: kubectl create deployment hello --image=nginx:1.30.6-alpine --replicas=2 --dry-run=client -o yaml > hello.yaml, then read it with cat hello.yaml

2. Apply it and wait: kubectl apply -f hello.yaml && kubectl rollout status deployment/hello

3. List its Pods with your own columns: kubectl get pods -l app=hello -o custom-columns=POD:.metadata.name,NODE:.spec.nodeName,PHASE:.status.phase

4. Remove it: kubectl delete -f hello.yaml, then kubectl get deployments

What you should see: in step 1, hello.yaml is a complete Deployment with replicas: 2 and the label app: hello, plus empty strategy: {}, resources: {} and status: {} lines you can delete. Step 2 ends with successfully rolled out. Step 3 shows two Pods in phase Running, one on each worker. Step 4 ends with No resources found in default namespace.

Remember

Check the context first. Keep the YAML as the description of what should exist, and before you apply a change, look at it with diff and let the server judge it with --dry-run=server.

Quick check
01You run kubectl scale deployment web --replicas=4. Later a teammate runs kubectl apply -f web.yaml, and the file says replicas: 2. How many Pods are there afterwards?
Incorrect — apply sends the file's values, including replicas. The lab went back from 4 to 2.
Incorrect — Nothing locks the count. scale only changes the same field apply sets.
Correct — The diff showed 4 live against 2 in the file, and apply restored the 2.
Incorrect — The Deployment has no memory of the scale command. It stays at the value last written.
02You want to know if the API server would accept a YAML file, without changing anything. Which command tells you?
Correct — The server runs every check and then discards the change. It rejected the bad name.
Incorrect — The client dry run does not send the object for validation. It accepted Web_App.
Incorrect — explain documents fields. It does not take a file or check one.
Incorrect — get -f reads the live objects the file names. It does not validate a change.
03A Deployment is not doing what you expect and you want its recent history, such as scaling steps. What do you run first?
Incorrect — jsonpath prints one field you already know. Events are separate objects.
Incorrect — explain documents fields in general. It knows nothing about your Deployment.
Incorrect — Worth knowing, but it says nothing about what the Deployment did.
Correct — describe ends with the object's recent events, such as ScalingReplicaSet.

Related