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.
| Command | What it creates |
|---|---|
create deployment name --image=image | Deployment; --replicas=3, --port=80, --image can be repeated (several containers) |
create service clusterip name --tcp=80:8080 | an in-cluster Service: service port 80 → container port 8080 |
create service nodeport name --tcp=80:8080 --node-port=30080 | a Service with a port on every node |
create service loadbalancer name --tcp=80:8080 | a Service with an external load balancer |
create service externalname name --external-name=host | a DNS alias for an external host |
create configmap name --from-literal=K=V | ConfigMap; --from-file=[key=]path, --from-env-file=file |
create secret generic name --from-literal=K=V | Secret; the same --from-file, --from-env-file |
create secret tls name --cert=crt --key=key | a Secret with a TLS certificate |
create secret docker-registry name --docker-server=… --docker-username=… --docker-password=… | access to a private image registry |
create namespace name | Namespace |
create job name --image=image -- command | Job (a one-off task) |
create cronjob name --image=image --schedule='0 3 * * *' -- command | CronJob (a scheduled task) |
create serviceaccount name | ServiceAccount |
create rolebinding name --role=role --serviceaccount=ns:name | a role binding (also --user, --group) |
create clusterrolebinding name --clusterrole=role --user=name | a cluster-wide role binding |
create ingress name --rule='host/path*=service:port' | Ingress (HTTP routing) |
create poddisruptionbudget name --selector=app=web --min-available=1 | PodDisruptionBudget |
create quota name --hard=pods=10,requests.cpu=2 | ResourceQuota |
create priorityclass name --value=1000 | PriorityClass |
Editing manifests without a cluster
| Command | What it does |
|---|---|
label -f file key=value --local -o yaml | add a label |
annotate -f file key=value --local -o yaml | add an annotation |
set image -f file container=image --local -o yaml | change the image |
set env -f file KEY=value --local -o yaml | add an environment variable |
set resources -f file --limits=cpu=200m,memory=128Mi --local -o yaml | set resources |
kustomize directory | build manifests from kustomization.yaml |
Working with a cluster
| Command | What it does |
|---|---|
apply -f file.yaml / -f directory/ / -k directory/ | create or update objects from manifests |
delete -f file.yaml / delete pod name | delete |
get pods / get all / get deploy,svc | list objects |
get pod name -o yaml / -o wide / -o jsonpath='{…}' | full description / with node and IP / a single field |
describe pod name | details 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 -- sh | a shell inside the container |
port-forward svc/name 8080:80 | forward a port to your machine |
rollout status/history/undo deploy/name | rollout progress / history / rollback |
scale deploy/name --replicas=3 | change the number of replicas |
explain deployment.spec | documentation for an object's fields |
config get-contexts / use-context name | list cluster contexts / switch |
Common flags
| Flag | What it does |
|---|---|
--dry-run=client | send nothing to the cluster |
-o yaml / -o json / -o name | output format |
-n name / -A | namespace / all namespaces |
-l app=web / -l 'tier in (front,back)' / -l '!canary' | filter by labels (label selector) |
-f file | work with the objects from a manifest |
-w | watch 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=clientwithout-o yamlprints onlydeployment.apps/web created (dry run). You see the manifest only with-o yaml.apply --dry-run=clientstill contacts the cluster: it needs the API schema. Without a cluster you can't "check a generated manifest via apply".kubectl runandcreate rolealso 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 byspec.selector.matchLabels. A typo in a label gives no error: the service simply ends up with no pods. - A Deployment's
selectorcan't be changed after creation — only the object can be recreated. - A Secret isn't encryption. The values in
dataare just base64-encoded and can be read withbase64 -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. Putkubectlflags before--.
See also
yq · base64 · docker-compose · ansible