Lesson 16 · Section 2: Core Concepts
Lesson 16: Pods with YAML: write, generate and fix a Pod manifest
What every line of a Pod manifest means, what the cluster does with the file after you apply it, how to let kubectl write it for you, and how to read the errors when it is wrong. · 22 min read · 5 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why describe a Pod in a file
In the previous lesson you started a Pod with one command, kubectl run. That is fine for a quick test, but the
command can reach only a few of a Pod's settings: an image, a port, some labels, some environment variables. A Pod
has more than a hundred possible fields (volumes, probes, security settings, a second container, node placement),
and the only way to reach all of them is to write the Pod down as a manifest: a YAML file that describes the
object you want.
A manifest has three more advantages that matter long after the exam:
- It is repeatable. The same file gives the same Pod today, tomorrow and on another cluster.
- It can be reviewed. A file can live in Git, be read by a colleague and be compared with what is running.
- It is the shape of everything else. A Deployment, a StatefulSet, a DaemonSet, a Job and a CronJob each contain a Pod template, which is a Pod manifest without the first two lines. Learn to read and write a Pod and you can read the largest part of every workload.
What a Pod manifest is made of
Parts:
- apiVersion (which API to speak), in pod.yaml
- kind (what to create), in pod.yaml
- metadata (who it is), in pod.yaml
- spec (what you want), in pod.yaml
- v1 (the core group)
- Pod (capital P, exactly)
- name, namespace (labels, annotations)
- containers (a list: one or more)
- name, image (ports, env, command)
Connections:
- apiVersion to v1
- kind to Pod
- metadata to name, namespace
- spec to containers
- containers to name, image: each item
Every Kubernetes object, of any kind, is described with the same four top-level fields:
| Field | What it answers | For a Pod |
|---|---|---|
apiVersion | Which API group and version understands this object? | v1 (the core group, which has no group name) |
kind | What type of object is it? | Pod |
metadata | Which object exactly? | name (required), namespace, labels, annotations |
spec | What do you want it to be? | containers (required), then everything optional |
Here is a complete, working manifest:
apiVersion: v1
kind: Pod
metadata:
name: web
namespace: shop
labels:
app: web
tier: frontend
spec:
containers:
- name: web
image: nginx:1.29
ports:
- containerPort: 80
Read it from the top:
apiVersion: v1. Pods, Services, ConfigMaps, Secrets and Namespaces belong to the oldest API group, called core, and its version string is justv1. Newer kinds live in named groups, which is why a Deployment saysapps/v1. If you are ever unsure,kubectl api-resourceslists the version next to every kind.kind: Pod. Kinds are case-sensitive and singular:Pod, neverpodorPods.metadata.name. The name must be unique among Pods in the namespace. Use lowercase letters, digits and hyphens; an uppercase letter or an underscore is rejected.metadata.namespace. Optional. Leave it out and the Pod goes into whatever namespacekubectlis pointed at (the-nflag, or the context's default).metadata.labels. Free key and value pairs that you invent. They do nothing by themselves, but Services, ReplicaSets andkubectl get -lall find Pods through them.spec.containers. A list, because a Pod can hold several containers. Each item needs aname(unique in the Pod) and animage. Everything else on a container is optional.
The fields you will add most often inside one container:
| Field | What it does | Worth knowing |
|---|---|---|
image | The image to run | Without a tag it means :latest, and then the image is pulled on every start |
command | Replaces the image's ENTRYPOINT | A list of strings: ["sleep", "3600"] |
args | Replaces the image's CMD | Set args alone to keep the image's entrypoint and change only its arguments |
env | Environment variables | A list of name and value; the value must be a string |
ports | Ports the container listens on | Informational: see the warning below |
resources | CPU and memory requests and limits | Covered with scheduling, later in the course |
Just enough YAML
YAML has many features, and Kubernetes manifests use three of them.
1. Maps: key: value. Indentation shows what belongs to what. Use spaces, two per level, and never a tab.
metadata:
name: web # name belongs to metadata
labels:
app: web # app belongs to labels, which belongs to metadata
2. Lists: a dash per item. The dash starts a new item, and the other keys of that item line up under the first key, not under the dash.
containers:
- name: web # first container starts here
image: nginx:1.29
- name: logger # second container starts here
image: busybox:1.37
3. Values have types. 80 is a number, true is a boolean, web is a string. Kubernetes checks the type of
every field, so quote a value when you need text that looks like something else:
env:
- name: WORKERS
value: "4" # env values must be strings: 4 without quotes is rejected
- name: DEBUG
value: "true" # same for true, false, yes, no, on, off
Under the hood · Two spellings you will meet for the same manifest
YAML allows the dash of a list item to sit at the same indentation as the key above it, and that is how kubectl
prints manifests:
spec:
containers:
- image: nginx:1.29 # dash directly under "containers"
name: web
This is the same data as the indented form used in this lesson. Both are valid; do not "fix" one into the other halfway through a file, because a list whose items start at different columns is the classic way to break it.
kubectl also sorts keys alphabetically, so image comes before name and labels before name. The order of
keys in a map never matters. The order of items in a list does: the first container in the list is the one that
kubectl logs and kubectl exec pick when you do not name a container.
A short list can also be written on one line, in square brackets: command: ["sh", "-c", "sleep 3600"]. And one
file can hold several objects, separated by a line containing only ---.
How it works: what the cluster does with your file
Parts:
- You (kubectl apply -f)
- kubectl (YAML to JSON)
- API server (validate, default)
- etcd (stores the Pod)
- Scheduler (picks a node)
- kubelet (on the chosen node)
- Containers (nginx:1.29 running)
Connections:
- You to kubectl: pod.yaml
- kubectl to API server: POST
- API server to etcd: save
- Scheduler to API server: sets nodeName
- kubelet and API server: watch, status
- kubelet to Containers: starts
Nothing in a cluster reads YAML except kubectl. When you run kubectl apply -f pod.yaml:
- kubectl parses the file, converts it to JSON and sends it over HTTPS to the API server, as a request to create a Pod in the namespace. If the YAML itself is broken, you get the error here and nothing leaves your terminal.
- The API server authenticates you, checks that you are allowed to create Pods, then validates the object:
unknown fields, wrong types and missing required fields are all rejected at this step. It fills in defaults,
runs the admission controllers and stores the Pod in etcd.
kubectlprintspod/web creatednow, although no container has started. - The scheduler watches for Pods with an empty
spec.nodeName, chooses a node and writes its name into the Pod. - The kubelet on that node watches for Pods assigned to it, asks the container runtime to pull the image and
start the containers, and keeps reporting what it sees into the Pod's
status.
That is why "created" and "running" are different things. A manifest with a misspelled image name is perfectly
valid: the API server accepts it, the scheduler places it, and only the kubelet finds out that the image does not
exist. You see it as ErrImagePull in kubectl get pod, not as an error from kubectl apply.
The cluster writes back
Parts:
- Your manifest (about 14 lines)
- API server adds (uid, defaults, token)
- Stored Pod (about 100 lines)
- Scheduler adds (spec.nodeName)
- kubelet writes (status: phase, podIP)
Connections:
- Your manifest to API server adds
- API server adds to Stored Pod
- Scheduler adds to Stored Pod
- kubelet writes to Stored Pod
Run kubectl get pod web -n shop -o yaml after creating the Pod above. Your fourteen lines have grown to about a
hundred. Everything new was added by the cluster:
| Added by | Examples |
|---|---|
| API server (defaults) | restartPolicy: Always, dnsPolicy: ClusterFirst, imagePullPolicy: IfNotPresent, terminationGracePeriodSeconds: 30, protocol: TCP on the port |
| API server (identity and admission) | uid, creationTimestamp, resourceVersion, serviceAccountName: default, a kube-api-access-… volume with the service account token, two tolerations |
| Scheduler | spec.nodeName |
| kubelet | The whole status: phase, conditions, podIP, hostIP, containerStatuses |
Two lessons follow from this. First, you write spec, the cluster writes status: a manifest never needs a
status section, and one that has it is ignored. Second, the stored object is the best documentation there is:
when you wonder what a default is, create the Pod and read it back.
Under the hood · Why most of a Pod cannot be changed afterwards
A Pod is a record of something that is already running on a node. Changing its volumes, its command or its ports would mean stopping the containers and building new ones, which is a different Pod. Kubernetes makes that explicit: after creation, the API server accepts changes to only a few fields of a Pod's spec.
spec.containers[*].imageandspec.initContainers[*].image(the kubelet restarts that container with the new image)spec.activeDeadlineSecondsspec.tolerations(you may only add to them)- CPU and memory
resources, on recent clusters, through the Pod's separateresizerequest (kubectl patch --subresource resize)
Labels and annotations are metadata, not spec, so they can always be changed.
Anything else is answered with Forbidden: pod updates may not change fields other than …. This is the reason
controllers exist: a Deployment handles a change to its Pod template by creating new Pods and removing the old ones
for you. With a bare Pod you do that replacement yourself.
Three ways to get a manifest, and three ways to send it
You will almost never write a manifest starting from an empty file. Choose the fastest source:
| Source | Command | Best when |
|---|---|---|
| Generate | kubectl run web --image=nginx:1.29 --dry-run=client -o yaml > pod.yaml | You are creating a new Pod (the usual case) |
| Export | kubectl get pod web -o yaml > pod.yaml | A similar Pod already runs in the cluster |
| Copy | An example from kubernetes.io, pasted and edited | You need a block kubectl run cannot write, such as a volume or a probe |
--dry-run=client means "build the object, print it, send nothing". Together with -o yaml it turns kubectl run
into a manifest generator.
And there are three verbs for sending a file to the cluster:
| Command | If the Pod does not exist | If it already exists |
|---|---|---|
kubectl create -f pod.yaml | Creates it | Fails with AlreadyExists |
kubectl apply -f pod.yaml | Creates it | Updates it to match the file (within what a Pod allows) |
kubectl replace --force -f pod.yaml | Creates it | Deletes it and creates it again |
apply is the safe default, and a later lesson is devoted to how it works. -f also accepts a directory, a URL, or
- to read the manifest from standard input.
Using it
- Generate
- Edit
- Dry run on the server
- Apply
- Verify
Example · From a task statement to a running Pod
In namespace shop, create a Pod named web that runs nginx:1.29, has the labels app=web and tier=frontend,
and declares container port 80.
Generate the manifest instead of typing it. Every requirement in this task has a flag:
kubectl create namespace shop
kubectl run web -n shop --image=nginx:1.29 --port=80 \
--labels=app=web,tier=frontend --dry-run=client -o yaml > pod.yaml
Look at what you got before you use it:
apiVersion: v1
kind: Pod
metadata:
labels:
app: web
tier: frontend
name: web
namespace: shop
spec:
containers:
- image: nginx:1.29
name: web
ports:
- containerPort: 80
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}
The extra lines (resources: {}, dnsPolicy, restartPolicy, status: {} and, on older versions,
creationTimestamp: null) are harmless defaults and empty values. Leave them; deleting them costs time and gains
nothing. Then test, apply and verify:
kubectl apply -f pod.yaml --dry-run=server # pod/web created (server dry run)
kubectl apply -f pod.yaml # pod/web created
kubectl get pod web -n shop -o wide --show-labels
--dry-run=server sends the object through the API server's real validation and admission, and stops just before
saving it. It catches everything except problems that only show up on the node, such as a wrong image name.
Example · Add what kubectl run cannot write
Extend the Pod: the web container gets the environment variable WORKERS=4, and a second container named ticker
runs busybox:1.37 and prints the date every ten seconds.
kubectl run can only create one container, so this is an edit. Open pod.yaml and make the containers list look
like this:
spec:
containers:
- image: nginx:1.29
name: web
env:
- name: WORKERS
value: "4"
ports:
- containerPort: 80
resources: {}
- image: busybox:1.37
name: ticker
command: ["sh", "-c"]
args: ["while true; do date; sleep 10; done"]
The new container is a new list item: a dash at exactly the same column as the dash of the first container. The Pod already exists and adding a container is not an allowed change, so replace it and check both containers:
kubectl replace --force -f pod.yaml
kubectl get pod web -n shop # READY shows 2/2
kubectl logs web -n shop -c ticker # one date line every ten seconds
Example · Fix a manifest from its error messages
You are given this file and told that it does not apply. It contains three separate mistakes:
apiVersion: apps/v1
kind: Pod
metadata:
name: cache
labels:
version: 7
spec:
containers:
- name: cache
imagee: redis:8
Apply it, read the error, fix one thing and apply again. You see one problem at a time, because each check runs only when the one before it has passed:
What kubectl apply -f says | What it means | The fix |
|---|---|---|
no matches for kind "Pod" in version "apps/v1" | That API group has no kind called Pod | apiVersion: v1 |
cannot unmarshal number into … metadata.labels of type string | A label value must be text | version: "7" |
unknown field "spec.containers[0].imagee" | The path points at a key the API does not know | Rename it to image |
With image misspelled, the container also had no image at all. If you had deleted the stray key instead of renaming
it, the next error would have been spec.containers[0].image: Required value: the same line of the file, seen by a
later check.
Tricks
Common mistakes
- A tab instead of spaces. The error is
found character that cannot start any token, with a line number. - A key at the wrong level.
containersindented undermetadata, orimageone level too shallow. The file is valid YAML, so the error comes from the API server asunknown field, and the path in the message shows where the server found the key. - A map where a list belongs.
containers:followed byname: webwithout a dash. Remember which fields are lists:containers,ports,env,volumes,volumeMounts,args,command. - The wrong
apiVersion.apps/v1for a Pod, orV1with a capital V. The message isno matches for kind. - Unquoted numbers and booleans where text is required. Label values, annotation values and
envvalues are strings. The message containscannot unmarshal number(orbool)… of type string. - Believing
created. The API server accepted the object; that is all. Always follow withkubectl get pod, and when the status is notRunning, read the Events at the bottom ofkubectl describe pod. - Editing a Pod as if it were a Deployment. Changing anything except the image of a running Pod is
Forbidden. Replace the Pod instead of fighting the error. - Exporting and re-applying without thinking. A manifest from
kubectl get pod -o yamlcarriesstatus,uid,resourceVersionandnodeName. RemovenodeNameat least, or the copy is pinned to the same node and skips the scheduler.
Recap
- A manifest describes the object you want:
apiVersion: v1,kind: Pod,metadata(who) andspec(what). - YAML structure is indentation and dashes: two spaces, no tabs, one dash per list item, quotes around text that looks like a number or a boolean.
- kubectl converts and sends; the API server validates, defaults and stores; the scheduler and kubelet do the rest
and write the
status. - Generate with
kubectl run … --dry-run=client -o yaml, look up fields withkubectl explain, test with--dry-run=server, then apply and verify. - Almost nothing in a running Pod's spec can be changed: use
kubectl replace --force -f.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.
A colleague left three Pod manifests behind. Each has a different mistake. Get all three Pods running.
Fix · Level 2 · standard · target 15 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.