Skip to main content

Anatomy of a `kubectl` Command

kubectl is the command-line interface for Kubernetes. It allows us to run commands against Kubernetes clusters. It is the most important command in Kubernetes, and we'll use it a lot.

I can't emphasize enough how important it is to write these commands manually until we internalize them. And, very importantly, make sure to set up kubectl completion, it will speed things up a lot.

$kubectlgetpodmy-pod-n my-namespace

Command

Specifies the operation that you want to perform on one or more resources, for example create, get, describe, delete.

Resource Type

Specifies the resource type. Resource types are case-insensitive and you can specify the singular, plural, or abbreviated forms.

Resource Name

Specifies the name of the resource. Names are case-sensitive. If the name is omitted, details for all resources are displayed, for example kubectl get pods.

Flags

Specifies optional flags. For example, you can use the -s or --server flags to specify the address and port of the Kubernetes API server.

Quick Reference

Common Commands

CommandWhat It DoesExample
getList resourceskubectl get pods
describeShow detailed infokubectl describe pod my-pod
applyCreate or update from filekubectl apply -f deployment.yaml
deleteRemove resourceskubectl delete pod my-pod
logsView container logskubectl logs my-pod
execRun command in containerkubectl exec -it my-pod -- /bin/sh
port-forwardForward local port to podkubectl port-forward my-pod 8080:80

Resource Shortcuts

Typing full resource names gets tedious. Use these shortcuts:

Full NameShortExample
podspokubectl get po
servicessvckubectl get svc
deploymentsdeploykubectl get deploy
namespacesnskubectl get ns
configmapscmkubectl get cm
persistentvolumeclaimspvckubectl get pvc
nodesnokubectl get no

Output Formats

Control how results are displayed with -o:

kubectl get pods -o wide          # More columns (node, IP)
kubectl get pod my-pod -o yaml # Full YAML definition
kubectl get pod my-pod -o json # JSON format
kubectl get pods -o name # Just names (for scripting)

Essential Flags

FlagPurposeExample
-nTarget namespacekubectl get pods -n production
-AAll namespaceskubectl get pods -A
-lFilter by labelkubectl get pods -l app=web
-wWatch for changeskubectl get pods -w
-fUse filekubectl apply -f manifest.yaml
--dry-run=clientPreview without applyingkubectl apply -f x.yaml --dry-run=client

Common Patterns

Check what's running:

kubectl get pods
kubectl get all # Pods, services, deployments, etc.

Debug a failing pod:

kubectl describe pod <name>       # Check events
kubectl logs <name> # Application logs
kubectl logs <name> --previous # Logs from crashed container

Get into a container:

kubectl exec -it <pod> -- /bin/sh

Generate YAML templates:

kubectl create deployment nginx --image=nginx --dry-run=client -o yaml

Find available fields:

kubectl explain pod.spec.containers