← Full reference

kubectl

The Kubernetes client — generating manifests with --dry-run=client, apply/get/describe, namespaces and labels

kubectl manages a Kubernetes cluster: it sends manifests (YAML descriptions of objects) to the API server and shows what's happening in the cluster. Some commands work without a cluster — for example, generating manifest skeletons.

There's no cluster in the sandbox. Only client-side operations work: kubectl create … --dry-run=client -o yaml (except create role/clusterrole), kubectl label/annotate/set with --local, kubectl kustomize, kubectl config, kubectl version --client. The commands apply, get, describe, run, expose, autoscale, explain, diff contact the server and fail with connection refused.

Syntax

kubectl <action> <type> [name] [flags]

Types are written in full or abbreviated: pods/po, deployments/deploy, services/svc, configmaps/cm, namespaces/ns, nodes/no.

kubectl create generators

With --dry-run=client -o yaml each of them prints a ready manifest.

CommandWhat it creates
create deployment name --image=imageDeployment; --replicas=3, --port=80, --image can be repeated (several containers)
create service clusterip name --tcp=80:8080an in-cluster Service: service port 80 → container port 8080
create service nodeport name --tcp=80:8080 --node-port=30080a Service with a port on every node
create service loadbalancer name --tcp=80:8080a Service with an external load balancer
create service externalname name --external-name=hosta DNS alias for an external host
create configmap name --from-literal=K=VConfigMap; --from-file=[key=]path, --from-env-file=file
create secret generic name --from-literal=K=VSecret; the same --from-file, --from-env-file
create secret tls name --cert=crt --key=keya Secret with a TLS certificate
create secret docker-registry name --docker-server=… --docker-username=… --docker-password=…access to a private image registry
create namespace nameNamespace
create job name --image=image -- commandJob (a one-off task)
create cronjob name --image=image --schedule='0 3 * * *' -- commandCronJob (a scheduled task)
create serviceaccount nameServiceAccount
create rolebinding name --role=role --serviceaccount=ns:namea role binding (also --user, --group)
create clusterrolebinding name --clusterrole=role --user=namea cluster-wide role binding
create ingress name --rule='host/path*=service:port'Ingress (HTTP routing)
create poddisruptionbudget name --selector=app=web --min-available=1PodDisruptionBudget
create quota name --hard=pods=10,requests.cpu=2ResourceQuota
create priorityclass name --value=1000PriorityClass

Editing manifests without a cluster

CommandWhat it does
label -f file key=value --local -o yamladd a label
annotate -f file key=value --local -o yamladd an annotation
set image -f file container=image --local -o yamlchange the image
set env -f file KEY=value --local -o yamladd an environment variable
set resources -f file --limits=cpu=200m,memory=128Mi --local -o yamlset resources
kustomize directorybuild manifests from kustomization.yaml

Working with a cluster

CommandWhat it does
apply -f file.yaml / -f directory/ / -k directory/create or update objects from manifests
delete -f file.yaml / delete pod namedelete
get pods / get all / get deploy,svclist objects
get pod name -o yaml / -o wide / -o jsonpath='{…}'full description / with node and IP / a single field
describe pod namedetails and events — the first place to look when something's wrong
logs pod [-c container] [-f] [--previous]container logs (of the previous run — --previous)
exec -it pod -- sha shell inside the container
port-forward svc/name 8080:80forward a port to your machine
rollout status/history/undo deploy/namerollout progress / history / rollback
scale deploy/name --replicas=3change the number of replicas
explain deployment.specdocumentation for an object's fields
config get-contexts / use-context namelist cluster contexts / switch

Common flags

FlagWhat it does
--dry-run=clientsend nothing to the cluster
-o yaml / -o json / -o nameoutput format
-n name / -Anamespace / all namespaces
-l app=web / -l 'tier in (front,back)' / -l '!canary'filter by labels (label selector)
-f filework with the objects from a manifest
-wwatch for changes (get -w)

Examples

# a Deployment skeleton into a file
kubectl create deployment web --image=nginx:1.27 --replicas=2 \
  --dry-run=client -o yaml > deployment.yaml

# a Service for it: the selector app=web matches the pod label
kubectl create service clusterip web --tcp=80:8080 --dry-run=client -o yaml

# an object right in the target namespace — metadata.namespace appears in the manifest
kubectl create deployment web --image=nginx -n staging --dry-run=client -o yaml

# ConfigMap and Secret
kubectl create configmap app-cfg --from-literal=MODE=prod --from-file=app.conf \
  --dry-run=client -o yaml
kubectl create secret generic db --from-literal=password=changeme --dry-run=client -o yaml

# Job and CronJob: the container command goes after --
kubectl create cronjob nightly --image=busybox --schedule='0 3 * * *' \
  --dry-run=client -o yaml -- date

# several objects in one file: YAML documents are separated by a --- line
{
  kubectl create deployment web --image=nginx --dry-run=client -o yaml
  echo '---'
  kubectl create service clusterip web --tcp=80:80 --dry-run=client -o yaml
} > app.yaml

# add a label and an environment variable to a ready manifest without a cluster
kubectl label -f deployment.yaml tier=frontend --local -o yaml
kubectl set env -f deployment.yaml MODE=prod --local -o yaml

# one field from a generated object
kubectl create deployment web --image=nginx --dry-run=client \
  -o jsonpath='{.spec.selector.matchLabels}'

# read a value from a Secret
kubectl create secret generic db --from-literal=password=changeme --dry-run=client \
  -o jsonpath='{.data.password}' | base64 -d

# in a real cluster (won't work here):
# kubectl apply -f deployment.yaml
# kubectl get pods -n staging -l app=web
# kubectl describe deployment web
# kubectl logs deploy/web --tail=50

How a Deployment and a Service are linked — through labels:

# Deployment: pods get the label app: web
spec:
  selector:
    matchLabels:
      app: web          # which pods the Deployment manages
  template:
    metadata:
      labels:
        app: web        # must match matchLabels
---
# Service: traffic goes to pods with the same label
spec:
  selector:
    app: web

Pitfalls

  • --dry-run=client without -o yaml prints only deployment.apps/web created (dry run). You see the manifest only with -o yaml.
  • apply --dry-run=client still contacts the cluster: it needs the API schema. Without a cluster you can't "check a generated manifest via apply".
  • kubectl run and create role also contact the server even with --dry-run=client. You'll have to write a Pod and a Role by hand or start from another generator.
  • Labels and selectors must match. A Service finds pods by spec.selector, a Deployment by spec.selector.matchLabels. A typo in a label gives no error: the service simply ends up with no pods.
  • A Deployment's selector can't be changed after creation — only the object can be recreated.
  • A Secret isn't encryption. The values in data are just base64-encoded and can be read with base64 -d.
  • Generated YAML contains noise: creationTimestamp: null, status: {}, resources: {}. That's normal; delete it if you like.
  • The default namespace is default. Without -n, commands in a cluster look there, and "missing" objects are often in another namespace.
  • Everything after -- goes to the container as the command. Put kubectl flags before --.

See also

yq · base64 · docker-compose · ansible