Cloud / Kubernetes Command line tool (kubectl) Interview questions
Last updated
1. What is kubectl?
kubectl is the official command-line client for Kubernetes. It turns the commands you type into REST calls to the cluster's API server, so you can create, inspect, update and delete resources without writing HTTP requests by hand.
It gets the server address, credentials and default namespace from a kubeconfig file, which lives at ~/.kube/config unless you override it. Day to day you use it to deploy manifests, read logs, open a shell in a container and check cluster health.
Every command follows the same shape:
kubectl [command] [TYPE] [NAME] [flags] kubectl get pods nginx -n demo -o wide
Take quiz
The kubelet on each node
The container runtime directly
etcd directly
The Kubernetes API server
The kubeconfig file at ~/.kube/config
A kubectl.yaml file in the current directory
The /etc/kubernetes/manifests folder
The KUBE_SERVER environment variable
2. How do you install kubectl?
Install it either from a package manager or by downloading the single static binary from the Kubernetes release server. Both give you the same tool.
| Platform | Common command |
| macOS | brew install kubectl |
| Windows | choco install kubernetes-cli |
| Linux (binary) | curl -LO https://dl.k8s.io/release/<version>/bin/linux/amd64/kubectl |
After downloading on Linux, make it executable and move it onto your PATH:
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl kubectl version --client
Keep the client within one minor version of the API server (older or newer) to stay inside the supported skew.
Take quiz
Exactly the same patch version only
One minor version older or newer
Up to two major versions older
There is no supported limit
brew cask kubernetes-api
apt install kubectl-mac
brew install kubectl
npm install -g kubectl
3. How do you check the kubectl and cluster version?
Run kubectl version. It prints the client version of your local binary and the server version reported by the API server.
Add --client when you only want the local binary and do not want kubectl to contact the cluster, which is handy in scripts and on a machine with no kubeconfig. Use -o yaml or -o json for machine-readable output.
kubectl version kubectl version --client kubectl version -o json
The old --short flag was removed in v1.28, so you will see it in older tutorials but it no longer works.
Take quiz
--local
--offline
--short
--client
The API server
The local kubeconfig file
The container runtime on your laptop
The kubectl release page
4. What is a kubeconfig file?
A kubeconfig is a YAML file that tells kubectl how to reach and authenticate to one or more clusters. It has three lists plus one pointer:
- clusters - API server address and CA data.
- users - credentials such as client certificates, tokens or exec plugins.
- contexts - a named combination of cluster, user and optional namespace.
- current-context - the context kubectl uses right now.
The default path is ~/.kube/config. Override it with --kubeconfig, or set the KUBECONFIG environment variable to a list of files and kubectl merges them.
kubectl config view --minify export KUBECONFIG=~/.kube/dev:~/.kube/prod
Take quiz
A pod, a node and a service
A cluster, a user and optionally a namespace
An image, a registry and a tag
A role, a binding and a secret
Place them in ~/.kube/conf.d and restart
Run kubectl config merge-all
Set KUBECONFIG to a colon-separated list of file paths
Rename them all to config.yaml
5. How do you list and switch kubectl contexts?
Use the kubectl config subcommands. They only edit your local kubeconfig and never touch the cluster.
kubectl config get-contexts # list all contexts kubectl config current-context # show the active one kubectl config use-context prod # switch
You can also run a single command against another context without switching, using --context:
kubectl --context=staging get nodes
That is safer than changing the active context, because a forgotten switch is a classic way to run a delete against production.
Many teams add tools such as kubectx to shorten this, but the built-in commands work everywhere. Print the active context in your shell prompt so you always know which cluster a command will hit.
Take quiz
kubectl switch cluster
kubectl set context --active
kubectl config select-cluster
kubectl config use-context
Pass --context=<name> on that command
Edit current-context in etcd
Restart the API server with a new flag
Use kubectl login --temporary
6. How do you set a default namespace for kubectl?
Update the current context so it carries a namespace. Every later command then runs in that namespace unless you pass -n.
kubectl config set-context --current --namespace=dev kubectl config view --minify | grep namespace
The --current flag edits the active context instead of requiring you to name it. Without a namespace set, kubectl falls back to default.
The -n flag always wins for a single command, and -A lists across every namespace.
This setting is stored only in your local kubeconfig. It does not change anything on the server, and a teammate using the same cluster keeps their own default.
Take quiz
--active
--current
--default
--self
kube-system
kube-public
default
The first one alphabetically
7. What does kubectl get do?
kubectl get lists one or more resources, or shows a single one by name. It is the command you run most often, because it gives a quick status table.
kubectl get pods kubectl get deploy web -o wide kubectl get svc,ingress -n prod kubectl get pods -w # watch for changes
Useful flags:
-o wide|yaml|json- more detail or the full object.-w- stream updates as they happen.--show-labels- add a LABELS column.-A- include all namespaces.
Take quiz
-f
--follow-all
-x
-w
The full object definition of each pod
Only the pod names
The container logs
Only the pods that failed
8. How do you list pods across all namespaces?
Add -A (short for --all-namespaces) to the get command. The output gains a NAMESPACE column.
kubectl get pods -A kubectl get pods -A -o wide
Combine it with a field selector to find trouble quickly, for example every pod that is not running:
kubectl get pods -A --field-selector=status.phase!=Running
Note that -A and -n do not mix; the all-namespaces flag takes precedence.
On large clusters this call returns a lot of data, so narrow it with -l or --field-selector, or use -o name to keep the output small. Add --sort-by=.metadata.namespace if you want grouped results.
Take quiz
-N
-A
-a
-ns
kubectl get pods --failed
kubectl get pods -A --only-errors
kubectl get pods -A --field-selector=status.phase!=Running
kubectl get pods -n all --bad
9. How do you create a namespace using kubectl?
Use the imperative command, or apply a small manifest if you want it tracked in Git.
kubectl create namespace dev # declarative equivalent apiVersion: v1 kind: Namespace metadata: name: dev
Namespaces divide a cluster into logical groups so teams can share it with separate names, quotas and RBAC rules. Deleting a namespace deletes everything inside it, so check the name before you run kubectl delete ns.
Cluster-scoped objects such as nodes and PersistentVolumes do not belong to any namespace.
Take quiz
They move to the default namespace
They are archived in etcd
Nothing, only the label is removed
They are all deleted with it
Node
Pod
Deployment
Service
10. How do you run a pod using kubectl run?
kubectl run creates a single Pod from an image. It does not create a Deployment, so nothing recreates the pod if it is deleted.
kubectl run nginx --image=nginx --port=80 kubectl run tmp --rm -it --image=busybox -- sh
The second form starts an interactive throwaway pod. -it attaches your terminal and --rm deletes the pod when you exit, which makes it ideal for testing DNS or connectivity from inside the cluster.
Treat it as a one-off pod with no controller behind it. For anything long-lived, create a Deployment instead.
Take quiz
Removes the image from the node
Deletes the pod after the session ends
Restarts the pod on failure
Removes the namespace
A ReplicaSet recreates it
The scheduler restores it
It stays deleted because no controller manages it
A DaemonSet brings it back
11. How do you create a deployment using kubectl?
Use kubectl create deployment with a name and image. Kubernetes then builds the chain Deployment, ReplicaSet, Pods for you.
kubectl create deployment web --image=nginx:1.27 --replicas=3 kubectl get deploy,rs,pods -l app=web
The command labels the pods app=web and sets the same label in the selector. If you need ports, probes or resource limits, generate YAML with --dry-run=client -o yaml, edit it and apply it.
Check the result with kubectl rollout status deploy/web, which waits until the new pods are ready. Remember the command creates only name, image and replicas, so probes, resource requests and environment variables must be added through YAML or later commands like kubectl set env.
Take quiz
name=web
deployment=web
run=web
app=web
A ReplicaSet
A DaemonSet
A StatefulSet
A Job
12. What does kubectl describe show?
kubectl describe prints a human-readable report about one resource: its spec, current status, related objects and, most usefully, the recent Events at the bottom.
kubectl describe pod web-7d9c-abcde kubectl describe node worker-1
Use it for questions like "why is this pod not starting?". The Events section reveals image pull errors, failed scheduling, failed probes and volume mount problems that get does not show. For the raw object, use kubectl get -o yaml instead.
The output also shows conditions such as PodScheduled, Ready and ContainersReady, plus each container's last termination reason. For nodes it adds allocated resources and taints, which helps explain why pods will not schedule.
Take quiz
The apiVersion line
The Events section
The creationTimestamp
The resourceVersion
kubectl describe --raw
kubectl show
kubectl get <resource> -o yaml
kubectl inspect
13. How do you view pod logs with kubectl?
Use kubectl logs. It reads the stdout and stderr that the container runtime has captured for that container.
kubectl logs web-7d9c-abcde kubectl logs -f web-7d9c-abcde --tail=100 kubectl logs web-7d9c-abcde -c sidecar kubectl logs web-7d9c-abcde --previous kubectl logs -l app=web --all-containers
-fstreams new lines.-cpicks a container in a multi-container pod.--previousshows the last crashed instance.--since=10mlimits the time window.
If a pod has been deleted or the node is gone, its logs are gone too. kubectl reads logs from the node, so long-term retention needs a log shipper such as Fluent Bit or a cloud logging agent.
Take quiz
--last-run
--crashed
--history
--previous
Use -c <container-name>
Use -n <container-name>
Use --pod-container
Append :name to the pod name only
14. How do you delete resources with kubectl?
Use kubectl delete by type and name, by file, or by label selector.
kubectl delete pod web-7d9c-abcde kubectl delete -f app.yaml kubectl delete pods -l app=web kubectl delete pod web --grace-period=0 --force
Deletion is graceful by default: the pod gets a SIGTERM and 30 seconds (by default) before SIGKILL. --force --grace-period=0 removes the API object immediately and should be a last resort, since the container may still be running on the node.
If a controller owns the pod, it will simply create a replacement. Delete the Deployment to stop that.
Take quiz
The Deployment is deleted too
The ReplicaSet creates a replacement pod
Nothing, the pod stays missing
The node is cordoned
Pauses the pod for zero seconds
Deletes the node
Removes the pod object immediately without waiting for graceful shutdown
Skips the confirmation prompt only
15. What is the purpose of kubectl apply?
kubectl apply is the declarative way to manage resources. You describe the desired state in YAML or JSON, and apply creates the object if it is missing or updates it to match if it exists.
kubectl apply -f deployment.yaml kubectl apply -f ./manifests/ -R kubectl apply -k overlays/prod
In client-side mode it stores the last submitted manifest in the kubectl.kubernetes.io/last-applied-configuration annotation and performs a three-way merge between that annotation, the live object and your new file. This lets it remove fields you deleted from the file without wiping fields set by other controllers.
Take quiz
Fails with AlreadyExists
Deletes and recreates it always
Ignores the file
Updates it to match the manifest using a merge
kubectl.kubernetes.io/last-applied-configuration
kubernetes.io/change-cause
deployment.kubernetes.io/revision
kubectl.kubernetes.io/restartedAt
16. How do you scale a deployment using kubectl?
Use kubectl scale with the target replica count.
kubectl scale deployment web --replicas=5 kubectl scale deployment web --current-replicas=3 --replicas=5 kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70
--current-replicas acts as a precondition: the scale only happens if the live count matches. For automatic scaling, kubectl autoscale creates a HorizontalPodAutoscaler.
If an HPA manages the deployment, it will overwrite your manual replica count on its next evaluation, and a replicas value in your applied YAML can fight with it.
You can also scale other controllers, such as a StatefulSet or ReplicaSet, with the same command. Scaling to --replicas=0 stops all pods while keeping the object, which is a common way to pause a workload.
Take quiz
A VerticalPodAutoscaler
A HorizontalPodAutoscaler
A second ReplicaSet
A ClusterAutoscaler node group
It sets the minimum replicas
It lists running replicas
It makes the scale conditional on the existing replica count
It resets the replica history
17. How do you run a command inside a container using kubectl exec?
Use kubectl exec, and put -- before the command so kubectl does not parse its flags as its own.
kubectl exec -it web-7d9c-abcde -- sh kubectl exec web-7d9c-abcde -c app -- env kubectl exec deploy/web -- cat /etc/nginx/nginx.conf
-i keeps stdin open and -t allocates a terminal, so together they give you an interactive shell. Without a -c flag, kubectl uses the pod's default container.
Minimal or distroless images often have no shell, so exec fails. In that case use an ephemeral container with kubectl debug.
Take quiz
To run the command as root
To enable debug logging
To run it on every pod
To separate kubectl flags from the command run in the container
Keep stdin open and allocate a terminal
Install and test the pod
Ignore errors and timeout
Inspect and trace the container
18. What is kubectl explain?
kubectl explain shows built-in documentation for any resource field, taken from the cluster's OpenAPI schema. It is the quickest way to check what a YAML field means without leaving the terminal.
kubectl explain pod kubectl explain pod.spec.containers.livenessProbe kubectl explain deployment.spec --recursive
Use dots to drill into nested fields. --recursive prints the whole tree of field names, which is useful when you are writing a manifest from scratch. Because the data comes from the live API server, it also reflects CRDs installed in that cluster.
Take quiz
Running containers in the cluster
Documentation for that field from the API schema
Logs of all containers
The pod's resource usage
Repeats the command on all pods
Explains every namespace
Prints the full tree of nested field names
Follows owner references
19. How do you expose a deployment as a service using kubectl?
Use kubectl expose. It creates a Service whose selector is copied from the deployment's pod labels.
kubectl expose deployment web --port=80 --target-port=8080 kubectl expose deployment web --type=NodePort --port=80 kubectl get svc web
--port is the port the Service listens on and --target-port is the container port that receives traffic. The default type is ClusterIP, reachable only inside the cluster. Use NodePort or LoadBalancer for external access.
Check which pods the Service actually selected with kubectl get endpoints web. An empty endpoints list almost always means the selector does not match the pod labels, or the pods are not ready.
Take quiz
NodePort
LoadBalancer
ExternalName
ClusterIP
The container port that receives the traffic
The node port on every host
The API server port
The port of the ingress controller
20. What are the common kubectl output formats?
The -o (or --output) flag controls how kubectl prints results.
| Format | Use |
wide |
Extra columns such as node and IP. |
yaml / json |
Full object, good for backups and diffs. |
name |
Only type/name, good for scripting. |
jsonpath |
Pick specific fields with a JSONPath expression. |
custom-columns |
Your own table layout. |
go-template |
Full templating logic. |
kubectl get pods -o name kubectl get pod web -o jsonpath='{.status.podIP}'
For scripting, prefer -o json or jsonpath to parsing the default table, because column layout can change between versions. -o name pairs well with xargs for bulk operations.
Take quiz
-o wide
-o name
-o short
-o ids
wide
yaml only
jsonpath
describe
21. How do you list the resource types supported by a cluster?
Run kubectl api-resources. It lists every resource type the API server serves, including those added by CRDs, with its short name, API group, whether it is namespaced and its kind.
kubectl api-resources kubectl api-resources --namespaced=false kubectl api-resources --api-group=apps kubectl api-resources -o wide # adds supported verbs
It answers questions like "what is the short name for persistentvolumeclaims?" (pvc) and "is this type namespaced?". To see supported API versions, use kubectl api-versions.
It is especially handy after installing an operator, because new CRD kinds show up in the list straight away. Add --verbs=list,get to see only the types you can read, which narrows the output to what is useful to you.
Take quiz
--cluster-only
--global
--scope=cluster
--namespaced=false
kubectl api-versions
kubectl api-groups --all
kubectl version --api
kubectl explain --versions
22. How do you add labels and annotations using kubectl?
Use kubectl label for labels and kubectl annotate for annotations. The difference matters: labels are used by selectors, annotations hold non-identifying metadata such as tool settings or notes.
kubectl label pod web env=prod kubectl label pod web env=staging --overwrite kubectl label pod web env- # remove label kubectl annotate pod web owner="team-a"
Changing an existing label needs --overwrite. A trailing dash after the key removes it. Be careful when editing labels that a Service or ReplicaSet selects on, because the pod may drop out of traffic or be orphaned.
Labels can also be applied in bulk, for example kubectl label pods -l app=web tier=frontend. Use --dry-run=server first if you are relabelling many objects, since a wrong selector can change a lot at once.
Take quiz
kubectl label pod web --delete env
kubectl label pod web env-
kubectl unlabel pod web env
kubectl label pod web env=null
Annotations are used by selectors
Labels cannot be changed
Labels are used for selection, annotations are not
Annotations are encrypted
23. What is the difference between kubectl create and kubectl apply?
create is imperative: it asks the API server to make a new object and fails with AlreadyExists if it is already there. apply is declarative: it creates the object if needed, otherwise it patches it to match your file.
| kubectl create | kubectl apply |
| Fails if the object exists. | Creates or updates. |
| No merge, no tracking annotation. | Three-way merge with last-applied annotation. |
| Good for one-off or generated objects. | Good for GitOps and repeatable pipelines. |
Note that mixing the two on one object causes confusion: objects made with create lack the last-applied annotation, so the first apply may behave unexpectedly. Use create --save-config if you plan to switch.
Take quiz
Updates it silently
Merges the fields
Deletes the old object
Fails with an AlreadyExists error
--save-config
--keep-state
--declarative
--track
24. What is the difference between kubectl apply and kubectl replace?
apply merges your manifest into the live object. replace swaps the whole stored object for the file you provide, so any field missing from the file is lost.
| apply | replace |
| Creates if missing. | Fails if the object does not exist. |
| Three-way merge, keeps fields set by others. | Overwrites the entire spec. |
| Cannot change immutable fields. | --force deletes and recreates it. |
Use replace --force only when you must change an immutable field such as a Job's selector or a Service's clusterIP, and accept the brief downtime that comes with delete and recreate.
As a rule, stay with apply for normal updates and treat replace as the tool for the rare case where you want the stored object to match the file exactly. Run kubectl diff first to see what would be lost.
Take quiz
Creates it
Returns a NotFound error
Creates it in default namespace
Applies a default template
Skips validation only
Forces a rolling update
Deletes and recreates the object
Replaces only the metadata
25. How does kubectl rollout manage deployment updates?
kubectl rollout controls and inspects rollouts of Deployments, DaemonSets and StatefulSets. A rollout starts whenever the pod template changes, for example a new image. Changing replicas does not trigger one.
- You change the template (
kubectl set imageorapply). - The Deployment creates a new ReplicaSet and scales it up while scaling the old one down, within
maxSurgeandmaxUnavailable. - You watch progress with
rollout status. - If it goes wrong,
rollout undoreturns to a previous revision.
kubectl rollout status deploy/web kubectl rollout history deploy/web kubectl rollout pause deploy/web kubectl rollout restart deploy/web
restart triggers a fresh rolling restart by stamping a new annotation on the template, which is the clean way to pick up a changed ConfigMap.
Take quiz
Changing the replica count
Adding a label to the Deployment metadata
Running kubectl get
A change to the pod template such as the image
Triggering a rolling restart without editing the image
Deleting all ReplicaSets
Rebooting the worker nodes
Resetting the revision history
26. How do you roll back a deployment using kubectl?
Use kubectl rollout undo. Without arguments it returns to the previous revision; with --to-revision it goes to a specific one.
kubectl rollout history deploy/web kubectl rollout history deploy/web --revision=3 kubectl rollout undo deploy/web kubectl rollout undo deploy/web --to-revision=2
Revisions are the old ReplicaSets that the Deployment keeps. The number retained is controlled by spec.revisionHistoryLimit, which defaults to 10. If you set it to 0, there is nothing to roll back to.
Only the pod template is restored. A manual scale or an HPA-driven replica count is not rolled back.
After the undo, check kubectl rollout status deploy/web and kubectl get rs to confirm the older ReplicaSet scaled back up. If your pipeline re-applies the newer manifest later, it will undo the rollback, so fix the source file as well.
Take quiz
spec.minReadySeconds
spec.revisionHistoryLimit
spec.progressDeadlineSeconds
spec.maxRevisions
The replica count of that revision
The Service configuration
The pod template of an earlier revision
The node assignments
27. How does kubectl port-forward work?
kubectl port-forward opens a local port on your machine and tunnels traffic through the API server to a port on a pod. It lets you reach an internal service without exposing it.
kubectl port-forward pod/web-7d9c-abcde 8080:80 kubectl port-forward svc/web 8080:80 kubectl port-forward deploy/web 8080:80 --address 0.0.0.0
The format is LOCAL:REMOTE. When you target a Service or Deployment, kubectl picks one pod and sticks to it, so there is no load balancing, and the tunnel breaks if that pod dies.
By default it binds to 127.0.0.1 only. Use --address carefully, since it can expose the forwarded port to your network.
Take quiz
The container port in the pod
The NodePort of the Service
The API server port
The local port on your machine
kubectl picks one pod and forwards to it only
Traffic is load balanced across all pods
It fails unless there is one replica
It forwards to the newest pod each request
28. How do you copy files to and from a pod using kubectl cp?
kubectl cp copies files between your machine and a container. Prefix the remote path with the pod name, and add -c when the pod has several containers.
kubectl cp ./app.conf web-7d9c-abcde:/tmp/app.conf kubectl cp web-7d9c-abcde:/var/log/app.log ./app.log -c app kubectl cp prod/web-7d9c-abcde:/data ./backup
Under the hood it streams a tar archive through exec, so the container image must contain the tar binary. Distroless images usually do not, and the command fails.
For large or repeated transfers, use a volume, object storage or kubectl exec with tar piping instead.
Trailing slashes and directory targets can behave differently from cp on Linux, so test with a small folder first. Preserving file permissions and ownership is not guaranteed, which matters for config or key files.
Take quiz
rsync
tar
scp
curl
Use the --ns-path flag only
Add it after the file name
Prefix it as namespace/pod:/path
It is not possible
29. What is the difference between kubectl exec and kubectl attach?
exec starts a new process inside a running container, such as a shell. attach connects your terminal to the stdin, stdout and stderr of the container's main process (PID 1) that is already running.
| kubectl exec | kubectl attach |
| Runs a new command in the container. | Joins the existing main process streams. |
| Safe to exit; the main process keeps running. | Ctrl+C may be sent to the main process and stop it. |
| Needs the binary to exist in the image. | Needs the pod to have stdin enabled for input. |
For troubleshooting, exec is almost always the right choice. Attach is mainly for interactive foreground programs, such as a REPL started by kubectl run -it.
Take quiz
A new shell process
The kubelet logs
The node's SSH session
The stdio of the container's main process
kubectl exec
kubectl attach with Ctrl+C
kubectl delete pod
kubectl run --force
30. How do you filter resources with label and field selectors?
Use -l (--selector) to filter on labels and --field-selector to filter on a small set of object fields.
kubectl get pods -l app=web,tier!=cache kubectl get pods -l 'env in (prod,staging)' kubectl get pods -l '!canary' kubectl get pods --field-selector=spec.nodeName=worker-1 kubectl get pods --field-selector=status.phase=Running
Label selectors support equality (=, !=) and set-based forms (in, notin, existence). Comma means AND.
Field selectors only work on fields the API server indexes, such as metadata.name, metadata.namespace, spec.nodeName and status.phase for pods. Arbitrary fields return an error.
You can use the same selectors with delete, logs and label, so kubectl delete pods -l app=web removes a whole group. Always run the matching get first to confirm what the selector hits.
Take quiz
Logical OR
Logical AND
A range
A fallback if the first fails
-l nodeName=<node>
--node-selector=<node>
--field-selector=spec.nodeName=<node>
--where node=<node>
31. How do you use JSONPath with kubectl get?
Pass -o jsonpath='<expression>' to print only the fields you need. Wrap the expression in single quotes so your shell leaves the braces alone.
kubectl get pod web -o jsonpath='{.status.podIP}' kubectl get pods -o jsonpath='{.items[*].metadata.name}' kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}' kubectl get nodes -o jsonpath='{.items[?(@.status.conditions[-1].type=="Ready")].metadata.name}'
range ... end loops over a list, [*] selects every element and ?(@...) filters. For a list result, remember the data sits under .items.
If the expression gets complicated, pipe -o json into jq instead.
JSONPath output is plain text with no newlines between items unless you add them, so use {"\n"} inside a range block for one item per line. Keys containing dots or slashes must be escaped, for example {.metadata.labels.app\.kubernetes\.io/name}. A missing field prints nothing rather than an error, which can hide typos.
Take quiz
Under .resources
Under .data
At the top level array
Under .items
range ... end
for ... done
foreach ... next
each ... stop
32. How do you use custom-columns and --sort-by in kubectl?
-o custom-columns builds your own table from JSONPath-style expressions, and --sort-by orders the rows by any field.
kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,IP:.status.podIP kubectl get pods --sort-by=.metadata.creationTimestamp kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' kubectl get pv --sort-by=.spec.capacity.storage
Each column is written as HEADER:.path. The expression after --sort-by is a JSONPath that must resolve to a number or string; sorting is done on the client, after the list is fetched.
Sorting by restartCount is a fast way to spot the noisiest pod.
Custom columns are handy for dashboards in a terminal, for example showing image and restart count side by side. A column can contain a wildcard path like .spec.containers[*].image, which prints all values comma-separated. If you need more logic than this, switch to go-template or jq.
Take quiz
path=HEADER
HEADER:.json.path
HEADER->path
{HEADER}.path
--order=age
--sort=name.desc
--sort-by=.metadata.creationTimestamp
--sort-by=.status.phase
33. How does kubectl diff help before applying changes?
kubectl diff shows what apply would change, without changing anything. It sends your manifest to the API server as a server-side dry run and compares the result with the live object, so defaults and admission mutations are included.
kubectl diff -f deployment.yaml echo $?
The exit code is useful in CI:
- 0 - no differences.
- 1 - differences found.
- greater than 1 - the command itself failed.
Set KUBECTL_EXTERNAL_DIFF to use your preferred diff tool. Because mutating webhooks run during the dry run, the diff is more accurate than comparing two YAML files locally.
A good habit is to run kubectl diff as a pull-request check, so reviewers see the real cluster impact, not just a YAML change. It does not show objects that would be pruned, and it needs read and dry-run create permissions.
Take quiz
0
2
127
1
It uses a server-side dry run that includes defaults and admission changes
It reads the etcd database directly
It downloads the container images
It ignores labels
34. What is server-side apply in kubectl?
With kubectl apply --server-side, the merge logic runs in the API server instead of in kubectl. The server tracks field ownership in metadata.managedFields, so it knows which manager (kubectl, a controller, an operator) set each field.
kubectl apply --server-side -f app.yaml kubectl apply --server-side --field-manager=ci-pipeline -f app.yaml kubectl apply --server-side --force-conflicts -f app.yaml
If two managers try to set the same field to different values, the server reports a conflict instead of silently overwriting it. --force-conflicts takes ownership anyway.
| Client-side apply | Server-side apply |
| Merge in kubectl using last-applied annotation. | Merge in API server using managedFields. |
| No conflict detection between tools. | Detects field conflicts. |
It also handles very large objects such as CRDs, which can exceed the annotation size limit used by client-side apply.
Take quiz
metadata.ownerReferences
metadata.managedFields
metadata.finalizers
spec.managers
Cancels the apply
Deletes the other manager
Takes ownership of conflicting fields and applies anyway
Merges both values together
35. How do you generate YAML with kubectl dry-run?
Add --dry-run=client -o yaml to an imperative command. kubectl builds the object and prints it without sending it to the cluster, giving you a ready-made manifest to edit.
kubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yaml kubectl run tmp --image=busybox --dry-run=client -o yaml -- sleep 3600 kubectl create namespace dev --dry-run=client -o yaml
There are two modes:
client- nothing is sent; validation is limited to what kubectl knows.server- the request goes to the API server, passes validation and admission, and is not persisted.
Use server when you want to know if the cluster would accept the object, including policy checks.
The generated YAML includes empty fields such as creationTimestamp: null and status: {}. Remove them before committing, and add what the generator cannot know: resource limits, probes and security context.
Take quiz
--preview --format=yaml
--simulate -o file
--dry-run=false -o yaml
--dry-run=client -o yaml
server sends the request to the API server for validation without saving
server saves the object, client does not
client runs admission webhooks, server does not
There is no difference
36. How does kubectl top work and what does it need?
kubectl top shows current CPU and memory usage for nodes and pods. It does not compute anything itself; it reads the Metrics API (metrics.k8s.io), which is served by metrics-server using data scraped from each kubelet.
kubectl top nodes kubectl top pods -n prod --containers kubectl top pods --sort-by=memory
If metrics-server is not installed, you get error: Metrics API not available. Install it first, and on some local clusters you may also need the kubelet insecure TLS option.
Values are a recent snapshot, not history, and they are not the same as requests or limits. For trends, use Prometheus or a similar monitoring system.
Typical use: run kubectl top nodes to find a hot node, then kubectl top pods -A --sort-by=cpu to find the pods responsible. Pods that were just created may take a minute or so to appear, because metrics are scraped on an interval.
Take quiz
Prometheus
metrics-server
kube-proxy
CoreDNS
Configured requests and limits only
Historical usage over 30 days
Current CPU and memory usage
Disk IOPS per volume
37. How do you troubleshoot a pod in CrashLoopBackOff?
CrashLoopBackOff means the container starts, exits and is restarted by the kubelet with an increasing delay (up to five minutes). Work through these steps:
kubectl get pod- check the RESTARTS count.kubectl describe pod- read Last State, Exit Code and the Events.kubectl logs <pod> --previous- read the output of the crashed run.- Check probes, environment variables, ConfigMaps and Secrets the app depends on.
- If there is no shell, use
kubectl debug.
| Exit code | Usual meaning |
| 1 | Application error. |
| 137 | SIGKILL, often OOMKilled (memory limit hit). |
| 143 | SIGTERM, graceful stop. |
A failing liveness probe can also cause the loop, even when the app itself is healthy but slow to start.
Another frequent cause is a missing dependency, such as a ConfigMap key or a database that is not reachable at startup. The application then exits with an error, which you will see in --previous logs. If the pod is killed so fast that no logs exist, run it with a sleep command through kubectl debug --copy-to and start the app by hand.
Take quiz
kubectl logs <pod> --crashed
kubectl describe logs <pod>
kubectl get logs --last
kubectl logs <pod> --previous
The container was killed by SIGKILL, often due to OOM
A normal successful exit
A failed image pull
A DNS lookup timeout
38. How do you troubleshoot a pod stuck in Pending?
Pending means the pod was accepted but has not been placed on a node, or its volumes are not ready. Start with the Events:
kubectl describe pod web-7d9c-abcde kubectl get events --field-selector involvedObject.name=web-7d9c-abcde
Look for a FailedScheduling message and match it to a cause:
- Insufficient cpu/memory - requests exceed what any node has free. Check
kubectl describe nodeandkubectl top nodes. - Taints not tolerated - add a toleration or use another node.
- Node selector or affinity mismatch - compare with
kubectl get nodes --show-labels. - Unbound PVC - run
kubectl get pvcand check the StorageClass.
If there are no scheduling events at all, check that the scheduler itself is running in kube-system.
Pending can also come from a quota limit in the namespace; check kubectl describe resourcequota. A pod that shows ContainerCreating instead is already scheduled, so the problem is probably an image pull or volume mount, not placement.
Take quiz
BackOff
FailedScheduling
Unhealthy
FailedMount only
The container used too much memory at runtime
The image is too large
No node has enough free memory for the pod's requests
The node ran out of disk
39. How do you view Kubernetes events sorted by time?
Events are ordinary objects, so you list them with kubectl get events, but the default order is not chronological. Sort them yourself:
kubectl get events --sort-by=.metadata.creationTimestamp kubectl get events -A --field-selector type=Warning kubectl events --for pod/web-7d9c-abcde
The newer kubectl events command sorts by time by default and can filter with --for and --types. It is easier to use than get events.
Events are short-lived. The API server keeps them for about one hour by default, so an issue from yesterday may leave no trace. Ship events to a log system if you need history.
Warning events are the first thing to read during an incident: failed mounts, probe failures, evictions and image pull errors all appear there. Add -w to watch new events live while you apply a fix.
Take quiz
Seven days
Forever until deleted
Ten seconds
About one hour
kubectl events --for pod/<name>
kubectl get logs --pod <name>
kubectl describe events <name>
kubectl history pod/<name>
40. What is kubectl debug and when should you use it?
kubectl debug helps you troubleshoot pods and nodes that you cannot easily inspect with exec, typically because the image has no shell. It supports three approaches:
- Ephemeral container - adds a temporary debug container to a running pod, sharing its process namespace with
--target. - Pod copy - creates a modified copy of the pod, for example with a different image or a command that does not crash.
- Node debug - starts a privileged pod on a node with the host filesystem mounted at
/host.
kubectl debug -it web-7d9c-abcde --image=busybox --target=app kubectl debug web-7d9c-abcde --copy-to=web-debug --container=app -- sh kubectl debug node/worker-1 -it --image=ubuntu
Ephemeral containers cannot be removed from the pod once added, and the original pod is not restarted. Use the copy approach when you need to avoid touching the live pod at all.
Take quiz
/node
/host
/mnt/root
/var/node
Selects the node to run on
Sets the image pull policy
Shares the process namespace of the named container
Copies the pod to a new namespace
41. How do you check permissions using kubectl auth can-i?
kubectl auth can-i asks the API server whether an action is allowed under RBAC and prints yes or no. It does not perform the action.
kubectl auth can-i create deployments -n dev kubectl auth can-i delete pods --as=jane -n prod kubectl auth can-i --list -n dev kubectl auth can-i get secrets --as=system:serviceaccount:dev:ci
--list prints every verb you may use in that namespace. --as and --as-group impersonate another user, which lets an admin check a role binding without logging in as that person.
Impersonation itself needs the impersonate permission, so regular users cannot use it.
This check only reads RBAC rules. It cannot tell you if an admission controller, such as a policy engine, will still reject the request. For a quick view of who you are authenticated as, newer clusters support kubectl auth whoami.
Take quiz
All users in the cluster
All RoleBindings in etcd
A list of denied requests from audit logs
All actions the current user may perform in the namespace
--as
--user-id
--switch
--sudo
42. How do you create ConfigMaps and Secrets using kubectl?
Both have imperative create subcommands that save you from writing YAML.
kubectl create configmap app-config --from-literal=LOG_LEVEL=debug --from-file=app.properties kubectl create configmap app-env --from-env-file=.env kubectl create secret generic db-cred --from-literal=password='S3cr3t' kubectl create secret docker-registry regcred --docker-server=reg.example.com --docker-username=me --docker-password=pw kubectl create secret tls web-tls --cert=tls.crt --key=tls.key
kubectl does the base64 encoding for you when it builds the Secret. Remember that base64 is an encoding, not encryption. Restrict access with RBAC and enable encryption at rest on the cluster.
Avoid putting real passwords in shell history; prefer --from-file or a secrets manager.
To review the YAML without creating anything, add --dry-run=client -o yaml. For GitOps, keep Secrets out of the repository in plain form and use sealed or external secret tooling instead.
Take quiz
kubectl create secret pull
kubectl create secret docker-registry
kubectl create secret generic --registry
kubectl create registrykey
Base64 is deleted after one hour
Secrets are stored in plain text on pods only
Base64 is an encoding that anyone can reverse
Base64 is only used for ConfigMaps
43. How do you decode a Kubernetes Secret with kubectl?
Secret values in .data are base64 encoded, so fetch the field and decode it.
kubectl get secret db-cred -o jsonpath='{.data.password}' | base64 -d kubectl get secret db-cred -o go-template='{{.data.password | base64decode}}'
The go-template form uses the built-in base64decode function and needs no extra tool. For keys with dots in the name, escape them in JSONPath, for example {.data.tls\.crt}.
Anyone with get permission on Secrets can run this, which is why that permission should be handed out sparingly.
To list every key at once, use kubectl get secret db-cred -o json | jq '.data | map_values(@base64d)'. Be careful with terminal scrollback and screen sharing, since decoded values are printed in plain text and can end up in history or logs.
Take quiz
decode64
unbase
b64plain
base64decode
{.data.tls\.crt}
{.data.tls.crt}
{.data['tls'.'crt']}
{.data/tls/crt}
44. What is the difference between kubectl cordon and kubectl drain?
cordon only marks a node unschedulable, so new pods are not placed there. Existing pods keep running. drain cordons the node and then evicts its pods so they restart elsewhere.
kubectl cordon worker-1 kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-data kubectl uncordon worker-1
| cordon | drain |
| Stops new scheduling only. | Stops scheduling and evicts pods. |
| No pod disruption. | Respects PodDisruptionBudgets. |
Drain refuses to proceed for DaemonSet pods and pods using emptyDir unless you pass the flags above. Pods without a controller are not recreated, so drain also needs --force for them, and they are lost.
A typical node upgrade goes: cordon, drain, upgrade, then uncordon. If a drain hangs, a PodDisruptionBudget is usually blocking an eviction because too few replicas are available. Check it with kubectl get pdb -A and fix the replica count rather than forcing the drain.
Take quiz
Evicts them immediately
Nothing, they keep running
Deletes them
Moves them to another namespace
--skip-system
--force-daemons
--ignore-daemonsets
--without-ds
45. How do you taint a node using kubectl?
Use kubectl taint nodes with key=value:effect. A taint repels pods unless they carry a matching toleration.
kubectl taint nodes gpu-1 hardware=gpu:NoSchedule kubectl taint nodes gpu-1 hardware=gpu:NoSchedule- # remove kubectl describe node gpu-1 | grep Taints
| Effect | Behaviour |
| NoSchedule | New pods without a toleration are not scheduled. |
| PreferNoSchedule | Scheduler tries to avoid the node, but may use it. |
| NoExecute | Also evicts running pods that do not tolerate it. |
A taint only repels. To make a pod prefer a node, combine it with a node selector or affinity.
Control plane nodes are tainted with node-role.kubernetes.io/control-plane:NoSchedule in most clusters, which is why ordinary pods do not land there. Use kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints[*].key to review them.
Take quiz
NoSchedule
PreferNoSchedule
EvictOnly
NoExecute
Repeat the taint command with a trailing dash
kubectl untaint node
kubectl delete taint gpu-1
kubectl label node hardware-
46. What are the patch types supported by kubectl patch?
kubectl patch changes part of a live object without editing the whole manifest. It supports three patch types, selected with --type:
| Type | Behaviour |
strategic (default) |
Kubernetes-aware merge; lists are merged by a merge key such as container name. |
merge |
JSON Merge Patch (RFC 7386); lists are replaced entirely. |
json |
JSON Patch (RFC 6902); explicit add, replace, remove operations by path. |
kubectl patch deploy web -p '{"spec":{"replicas":4}}' kubectl patch deploy web --type=json -p='[{"op":"replace","path":"/spec/template/spec/containers/0/image","value":"nginx:1.27"}]'
Strategic merge does not work on custom resources, so use merge or json for CRDs.
Prefer apply for changes you want tracked in Git, and use patch for quick operational changes or scripts, such as toggling a flag or suspending a CronJob with -p '{"spec":{"suspend":true}}'. A patch targets a subresource with --subresource=status when needed.
Take quiz
merge
strategic
json
replace
strategic
merge
json
apply
47. How do you use kubectl wait in scripts and pipelines?
kubectl wait blocks until a resource meets a condition or a timeout expires. It replaces fragile sleep loops in CI.
kubectl wait --for=condition=Available deploy/web --timeout=120s kubectl wait --for=condition=Ready pod -l app=web --timeout=60s kubectl wait --for=delete pod/web-7d9c-abcde --timeout=30s kubectl wait --for=jsonpath='{.status.phase}'=Running pod/web
It exits with code 0 on success and non-zero on timeout, so a pipeline step fails correctly. Use --for=delete to confirm cleanup finished and --for=jsonpath for anything without a standard condition.
Create the resource first. Waiting on an object that does not exist yet fails immediately with NotFound.
A common CI sequence is apply, then wait --for=condition=Available, then smoke tests. Choose a timeout longer than your readiness probe and image pull time, otherwise the step fails on a healthy rollout.
Take quiz
0
It never exits
Always 200
A non-zero code
--for=delete
--for=gone
--until=absent
--for=condition=Deleted
48. How do you use kubectl with Kustomize?
kubectl has Kustomize built in. A directory with a kustomization.yaml lists base resources and the changes to layer on top, so you avoid copying whole manifests per environment.
kubectl kustomize overlays/prod # render only kubectl apply -k overlays/prod # render and apply kubectl diff -k overlays/prod
A typical layout has a base/ folder and one overlay per environment. An overlay can set namePrefix, namespace, images, replicas and patches:
resources: - ../../base namespace: prod images: - name: web newTag: "1.27.2" patches: - path: replicas.yaml
The Kustomize version embedded in kubectl lags behind the standalone binary, so newer features may only be available if you install it separately.
Because the output is plain YAML, you can pipe it elsewhere, for example kubectl kustomize . | kubectl diff -f -. Use configMapGenerator to add a content hash to ConfigMap names, so pods restart automatically when the config changes.
Take quiz
-K
-k
--overlay
-f --build
Applies the manifests to the cluster
Deletes the overlay
Renders the final YAML without applying it
Validates only the cluster version
49. What are kubectl plugins and how does krew help?
A kubectl plugin is any executable on your PATH whose name starts with kubectl-. kubectl runs it when you type the matching subcommand.
cat > /usr/local/bin/kubectl-hello <<'EOF' #!/bin/sh echo "Hello from $(kubectl config current-context)" EOF chmod +x /usr/local/bin/kubectl-hello kubectl hello kubectl plugin list
Dashes in the file name become spaces in the command, so kubectl-foo-bar runs as kubectl foo bar. Underscores in the file name become dashes in the command.
krew is the plugin manager. It installs, updates and removes plugins from a curated index.
kubectl krew install ctx ns tree kubectl krew update
Plugins run with your credentials, so install only ones you trust.
Popular krew plugins include ctx and ns for switching context and namespace, tree for ownership hierarchy, and neat for cleaning YAML. If a plugin does not run, check that the file is executable and that its name does not clash with a built-in command, which always takes precedence.
Take quiz
hello-kubectl
kubectl_plugin_hello
k8s-hello
kubectl-hello
Installs and updates kubectl plugins
Encrypts the kubeconfig file
Creates cluster nodes
Compiles Go manifests
50. Explain the internal working of kubectl when you run a command?
When you run a command, kubectl turns it into one or more authenticated REST calls. Here is the flow for kubectl get pods:
sequenceDiagram
participant U as User
participant K as kubectl
participant C as Local cache
participant A as API server
U->>K: kubectl get pods
K->>K: Load kubeconfig, pick context
K->>C: Read discovery cache
C-->>K: Resource to API path mapping
K->>A: GET /api/v1/namespaces/default/pods (with credentials)
A->>A: Authenticate, authorize, return list
A-->>K: JSON list of pods
K-->>U: Print table
- Load config - kubectl reads the kubeconfig (or
KUBECONFIG) and picks the current context. - Discovery - it asks the API server which resources exist and caches the answer under
~/.kube/cache, sopodsmaps to/api/v1/pods. - Authentication - it attaches the certificate, token or exec-plugin credential.
- Request - it sends the HTTPS call; the server authenticates, authorizes (RBAC), runs admission and returns the data.
- Printing - kubectl formats the result as a table, YAML or JSON.
Commands like logs -f, exec and port-forward upgrade the connection to a streaming protocol (WebSocket or SPDY) through the API server to the kubelet. Use -v=8 to print the exact HTTP requests and responses.