mailwal

Kubernetes Pod YAML Explained Line by Line: Understand Every Field, Write Better YAML, Deploy with Confidence 🚀

Arvind Verma

Kubernetes Pod YAML Explained Line by Line: Understand Every Field, Write Better YAML, Deploy with Confidence 🚀

A Practical Kubernetes Guide for DevOps Engineers, Beginners, and Interview Preparation

Have you ever looked at a Kubernetes YAML file and wondered why it contains so many fields?

You see apiVersion, kind, metadata, spec, containers, volumes, securityContext, tolerations, and several other settings. Everything looks important, but understanding what each field actually does is what separates someone who can copy a manifest from an engineer who can troubleshoot it in production.

Here is the reality: Kubernetes does not run your YAML file just because it looks correct. The API server validates the resource, the scheduler finds a suitable node, and the kubelet works to bring the Pod into the desired state.

A small mistake in a manifest can lead to an application that never starts, a container that repeatedly restarts, a Pod that remains pending, or a workload that runs with unnecessary privileges.

In this guide, we will break down a Kubernetes Pod manifest line by line, understand why each field matters, explore practical production scenarios, and prepare for common interview questions.

By the end, you should be able to read a Pod manifest, explain its purpose, identify common mistakes, and troubleshoot it with greater confidence. ☸️


PART 1: Understanding the Structure of a Kubernetes Pod YAML

1. What Is a Kubernetes Pod?

A Pod is the smallest deployable unit in Kubernetes. It can contain one or more containers that share certain resources, including a network namespace and, when configured, shared volumes.

Think of a Pod as the environment in which your application containers run.

For example, an application might have a container running NGINX. Kubernetes manages the Pod according to the desired state defined in the manifest.

In production, most application workloads are managed through higher-level controllers such as Deployments and StatefulSets rather than by creating standalone Pods manually. Standalone Pods are still useful for learning and troubleshooting.

2. The Complete Pod YAML Example

The infographic illustrates a Pod manifest containing configuration, storage, scheduling rules, security settings, and an init container.

Here is a readable version of that example:

apiVersion: v1
kind: Pod

metadata:
  name: techops-pod
  labels:
    app: techops
    tier: backend

spec:
  containers:
    - name: techops-container
      image: nginx:1.23

      ports:
        - containerPort: 80

      env:
        - name: ENV
          value: production

      volumeMounts:
        - name: config-volume
          mountPath: /usr/share/nginx/html

  volumes:
    - name: config-volume
      configMap:
        name: techops-config

  restartPolicy: Always

  nodeSelector:
    disktype: ssd

  tolerations:
    - key: "special-taint"
      operator: "Equal"
      value: "true"
      effect: "NoExecute"

  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000

  initContainers:
    - name: init-techops
      image: busybox
      command:
        - sh
        - -c
        - "echo Init; sleep 5"

Important: This is an educational example based on the illustrated manifest, not a complete production-ready deployment. The referenced ConfigMap must exist, the scheduling requirements must be satisfiable, and the container images and security settings must be appropriate for your environment.

Also, nginx:1.23 and an unpinned busybox image are not recommendations for a new production deployment. Use maintained images and pin versions or digests according to your organisation’s image-management policy.

Let’s understand every major field.

3. apiVersion: v1

apiVersion: v1

What does it mean?

It tells Kubernetes which API version defines the resource.

Pods use the core API group, represented by v1.

Why do we need it?

Kubernetes supports different API groups and versions for different resources. The API server needs to know how to interpret the resource definition.

Interview answer

“apiVersion specifies the Kubernetes API version used to define a resource. For a Pod, we use v1, which belongs to the core API group.”

Memory trick: apiVersion tells Kubernetes which API definition to use.

4. kind: Pod

kind: Pod

What does it mean?

It identifies the type of Kubernetes resource being created.

Here, the resource is a Pod.

Other examples include:

  • Deployment

  • Service

  • ConfigMap

  • Secret

  • StatefulSet

  • DaemonSet

Production example

If you define kind: Service, Kubernetes interprets the manifest as a Service resource rather than a Pod.

The fields supported under spec depend on the resource type. A Service and a Pod do not share the same specification structure.

Interview answer

“kind identifies the Kubernetes object type. Together, apiVersion and kind tell the API server which resource definition to use.”

Memory trick: kind answers, “What am I creating?”

5. metadata: Name and Labels

metadata:
  name: techops-pod
  labels:
    app: techops
    tier: backend

Metadata describes and identifies the resource.

metadata.name

The name identifies the Pod within its namespace.

name: techops-pod

You use the name when inspecting or troubleshooting the resource:

kubectl get pod techops-pod
kubectl describe pod techops-pod
kubectl logs techops-pod

metadata.labels

Labels are key-value pairs attached to Kubernetes objects.

labels:
  app: techops
  tier: backend

Labels can be used by selectors to group and identify resources.

For example, a Service might select Pods labelled app: techops.

selector:
  app: techops

The Service selector and the Pod labels must match for the Service to select the intended Pods.

Why are labels important?

Labels support application grouping, service discovery, deployment organisation and operational queries.

kubectl get pods --show-labels
kubectl get pods -l app=techops

Common interview trap

A label does not automatically expose an application or route traffic to it. A Service or another component must use an appropriate selector or routing configuration.

Memory trick: Names identify objects; labels help group and select them.

6. spec: The Desired State

spec:

The spec section describes the desired configuration of the resource.

For a Pod, this includes containers, volumes, scheduling rules, restart policy and security-related settings.

Kubernetes uses controllers and node-level components to work toward the declared state.

Production example

If a Pod specifies an image that cannot be pulled, Kubernetes cannot successfully start the container even though the YAML itself may be syntactically valid.

This distinction is important: valid YAML does not guarantee a working workload.

Interview answer

“spec defines the desired configuration of the Kubernetes resource. For a Pod, it specifies the containers and other settings required to run the workload.”

7. containers: Where the Application Runs

containers:
  - name: techops-container
    image: nginx:1.23

A Pod can contain one or more containers.

name

name: techops-container

The container name identifies a container within the Pod.

For a Pod with multiple containers, you can specify the container when reading logs:

kubectl logs techops-pod -c techops-container

image

image: nginx:1.23

The image provides the application and its runtime environment.

Kubernetes uses the configured container runtime to obtain and run the image.

In production, image selection should include security scanning, trusted registries, maintenance planning and appropriate version pinning.

Common interview trap

The container image version is not the same thing as the Kubernetes API version.

apiVersion: v1 describes the Kubernetes resource API, while image: nginx:1.23 identifies the application image and tag.

Memory trick: The container defines what runs; the image defines what the container starts from.

8. ports and containerPort

ports:
  - containerPort: 80

This declares that the container is expected to listen on port 80.

It is useful documentation and can be referenced by some Kubernetes configurations, but it does not itself publish the application to the internet.

How do you expose the application?

Depending on the requirement, you might use:

  • A ClusterIP Service for internal cluster access.

  • A NodePort Service for access through node ports.

  • A LoadBalancer Service for an external load-balancer integration.

  • An Ingress resource with a compatible Ingress controller for HTTP or HTTPS routing.

Interview answer

“containerPort documents the port on which the container expects to listen. It does not expose the Pod externally. A Service or another suitable networking component is needed for traffic access.”

Memory trick: Declaring a port is not the same as publishing a service.


PART 2: Configuration, Storage, Scheduling and Security

9. env: Environment Variables

env:
  - name: ENV
    value: production

Environment variables allow applications to receive configuration without embedding every setting into the container image.

In this example, the application receives an environment variable named ENV with the value production.

Why do we need it?

The same application image may run in development, staging and production with different configuration.

For example, the environment may determine log verbosity, feature flags or an application mode.

Common interview trap

Do not place passwords, access tokens or other sensitive values directly in plain-text manifests committed to a repository.

Use Kubernetes Secrets or an appropriate external secret-management integration for sensitive information, together with access controls and secure delivery.

Memory trick: Environment variables configure application behaviour at runtime.

10. volumeMounts: Mounting Storage Inside a Container

volumeMounts:
  - name: config-volume
    mountPath: /usr/share/nginx/html

A volume mount specifies where a volume appears inside the container’s filesystem.

Here, the volume named config-volume is mounted at /usr/share/nginx/html.

Why do we need it?

Volumes can provide configuration files, shared files or persistent data, depending on the volume type.

For example, a ConfigMap-backed volume can provide configuration files to an application.

Important detail

Mounting a volume over an existing directory can hide the files that were previously visible at that location inside the container.

For an NGINX image, mounting a ConfigMap over the default HTML directory can therefore change which files NGINX serves.

Interview answer

“volumeMounts defines the mount point of a Pod volume inside a particular container. The volume must be declared under the Pod’s volumes section.”

11. volumes: Defining the Storage Source

volumes:
  - name: config-volume
    configMap:
      name: techops-config

This declares a volume named config-volume backed by a ConfigMap named techops-config.

The ConfigMap must exist in the same namespace as the Pod unless the deployment process creates it before the Pod starts.

How does it work?

The Pod declares the volume source. A container references that volume using volumeMounts.

A volume can be backed by different sources, including ConfigMaps, Secrets and persistent volume claims.

Production example

An NGINX workload can consume a ConfigMap containing HTML or configuration files without embedding those files in a custom image.

For long-lived application data, a PersistentVolumeClaim may be more suitable than a ConfigMap.

Common interview trap

A ConfigMap volume is not a database or a replacement for persistent application storage.

Memory trick: volumes defines the source; volumeMounts defines where the source appears in the container.

12. restartPolicy: Always

restartPolicy: Always

This setting determines how Kubernetes handles containers that exit.

For ordinary Pods, the supported restart policies are Always, OnFailure and Never.

  • Always: Restart containers when they terminate, regardless of exit status.

  • OnFailure: Restart containers when they terminate unsuccessfully.

  • Never: Do not restart terminated containers.

A Pod managed by a Deployment normally uses Always.

Important distinction

A restart policy does not guarantee that an application will recover successfully. A container may continue failing because of a bad configuration, a missing dependency or an application bug.

Interview answer

“restartPolicy controls whether containers in the Pod are restarted after termination. For Pods managed by a Deployment, the policy is normally Always.”

13. nodeSelector: Scheduling on Suitable Nodes

nodeSelector:
  disktype: ssd

A nodeSelector restricts a Pod to nodes that have matching labels.

In this example, a node must have the label disktype=ssd to satisfy the selector.

Why do we need it?

Some workloads have specific placement requirements, such as hardware characteristics or separation between workload types.

How do you troubleshoot a Pod that remains Pending?

kubectl get nodes --show-labels
kubectl describe pod techops-pod
kubectl get events --sort-by=.metadata.creationTimestamp

If no eligible node has the required label, the Pod may remain Pending.

Other scheduling constraints, insufficient resources and taints can also prevent scheduling.

Common interview trap

A nodeSelector does not install an SSD or verify that the underlying storage is appropriate. It matches labels assigned to nodes.

Memory trick: nodeSelector filters eligible nodes by labels.

14. tolerations: Allowing Pods onto Tainted Nodes

tolerations:
  - key: "special-taint"
    operator: "Equal"
    value: "true"
    effect: "NoExecute"

A toleration allows a Pod to tolerate a matching taint.

Taints and tolerations are often used to reserve nodes for specific workloads or prevent unsuitable workloads from running on particular nodes.

How does it work?

A node taint can repel Pods that do not have a matching toleration.

The NoExecute effect can also evict existing Pods that do not tolerate the taint.

The example toleration matches a taint with the same key, value and effect.

Common interview trap

A toleration does not force a Pod onto a particular node. It permits the Pod to tolerate a matching taint. A separate scheduling constraint may still be required to select the intended node.

Memory trick: Taints repel; tolerations permit.

15. securityContext: Running with Appropriate Privileges

securityContext:
  runAsUser: 1000
  runAsGroup: 3000
  fsGroup: 2000

Security contexts control aspects of the security configuration for a Pod or container.

In this example:

  • runAsUser specifies the user ID for the container processes.

  • runAsGroup specifies the primary group ID for the container processes.

  • fsGroup can influence group ownership and access to supported mounted volumes.

Why do we need it?

Running applications with unnecessary privileges increases the impact of a compromise.

Production workloads should use the least privilege necessary and avoid running as root when the application can operate safely without it.

Important detail

These settings do not automatically guarantee that every file or mounted volume will have the expected permissions. The behaviour depends on the image, volume type, filesystem and Kubernetes configuration.

Interview answer

“I use securityContext to configure runtime security properties such as the process user and group. I prefer non-root execution where supported, validate filesystem permissions and combine these settings with least-privilege access controls.”

Memory trick: Restrict the process before an incident forces you to investigate why it had too much access.

16. initContainers: Preparing the Environment

initContainers:
  - name: init-techops
    image: busybox
    command:
      - sh
      - -c
      - "echo Init; sleep 5"

Init containers run before the regular application containers start.

They are useful for preparation tasks such as validating configuration, generating files in a shared volume or waiting for a prerequisite to become available.

How does it work?

Kubernetes runs init containers to completion before starting the regular containers in the Pod.

If an init container fails, Kubernetes applies the Pod’s restart behaviour and the init container may run again.

Production example

An init container can validate that required configuration files are present before the main application starts.

However, avoid using a simple sleep as the sole method of determining whether a dependency is ready. An explicit readiness check is more reliable.

Common interview trap

Init containers are not the same as sidecar containers.

An init container normally completes its task before application containers start. A sidecar generally runs alongside the main application.

Memory trick: Init containers prepare; application containers serve.


PART 3: Deploy, Troubleshoot and Explain It Like an Engineer

17. How Does a Pod Start?

Understanding the startup process helps you explain Kubernetes beyond YAML syntax.

A simplified flow looks like this:

  1. You submit the manifest using kubectl.

  2. The API server validates and stores the Pod specification.

  3. The scheduler selects a suitable node if the Pod has not already been assigned one.

  4. The kubelet on that node works to ensure the Pod’s containers are running.

  5. The container runtime obtains the images and starts the containers.

  6. Init containers complete before ordinary application containers start.

  7. The application begins serving traffic when it is operational and any required readiness checks succeed.

The exact behaviour depends on the Pod configuration and the workload.

18. How to Deploy the Example Safely

Before applying the manifest, make sure the referenced ConfigMap exists.

Create a simple ConfigMap for the example:

kubectl create configmap techops-config \
  --from-literal=index.html='<h1>Hello from Kubernetes</h1>'

Save the Pod YAML in a file named pod.yaml.

Validate the manifest locally where supported:

kubectl apply --dry-run=client -f pod.yaml

Apply the resource:

kubectl apply -f pod.yaml

Inspect its status:

kubectl get pod techops-pod -o wide
kubectl describe pod techops-pod
kubectl logs techops-pod

If the Pod does not start, inspect the events and container logs instead of repeatedly deleting and recreating it.

A note about this demonstration

The sample includes a node selector and a toleration. The cluster must have an eligible node with the required disktype=ssd label, and any relevant taints must be compatible with the Pod’s tolerations. Otherwise, the Pod may remain Pending.

The sample also uses a ConfigMap-backed volume mounted over NGINX’s default HTML directory. That is useful for demonstrating configuration mounts, but a production configuration should be deliberately designed and tested.

19. Common Kubernetes YAML Mistakes

Mistake 1: Incorrect indentation

YAML uses indentation to express structure. Incorrect indentation can make a manifest invalid or change its meaning.

Mistake 2: Using the wrong image tag

A missing or unavailable image can cause image-pull failures.

Mistake 3: Assuming containerPort exposes the application

A declared container port does not create a public endpoint.

Mistake 4: Forgetting a referenced ConfigMap or Secret

A Pod can fail to start correctly when a required configuration resource is missing or invalid.

Mistake 5: Using scheduling rules without checking the cluster

A nodeSelector or taint requirement can leave the Pod unscheduled.

Mistake 6: Running containers as root unnecessarily

Prefer an appropriate non-root configuration when supported by the image and application.

Mistake 7: Using latest without a deployment strategy

Mutable image tags make it harder to identify exactly which version is running and to reproduce a deployment.

Mistake 8: Confusing a running container with a healthy application

A process can be running while the application is unable to serve requests. Use suitable health checks and application-level monitoring.

20. Troubleshooting Commands Every DevOps Engineer Should Know

# List Pods
kubectl get pods

# Inspect the Pod in detail
kubectl describe pod techops-pod

# Read application logs
kubectl logs techops-pod

# Inspect recent events
kubectl get events --sort-by=.metadata.creationTimestamp

# Check nodes and their labels
kubectl get nodes --show-labels

# View the Pod YAML stored by the API server
kubectl get pod techops-pod -o yaml

# Validate a manifest before applying it
kubectl apply --dry-run=client -f pod.yaml

# Delete the example Pod when finished
kubectl delete pod techops-pod

Use these commands as investigation tools. The goal is not to run every command in every incident, but to select the ones that provide evidence about the failure.

21. Interview Questions You Should Practise

Q1. What is the difference between apiVersion and kind?

apiVersion identifies the API version, while kind identifies the resource type.

Q2. Does containerPort expose a Pod externally?

No. It documents the container port. External or internal service access requires suitable networking configuration.

Q3. What is the difference between volumes and volumeMounts?

volumes defines the storage source at Pod level. volumeMounts defines where a container sees that volume.

Q4. What is the difference between a node selector and a toleration?

A node selector restricts placement to matching node labels. A toleration allows a Pod to tolerate a matching taint.

Q5. Why use init containers?

They perform preparation tasks that must complete before ordinary application containers start.

Q6. Why use a security context?

It configures runtime security properties, including user and group IDs, to support least-privilege execution.

Q7. How would you investigate a Pod that remains Pending?

I would inspect kubectl describe pod, recent events, node labels, taints, resource availability and scheduling constraints to identify why no suitable node was selected.

Q8. How would you investigate a container that keeps restarting?

I would inspect the Pod description, current and previous logs, termination reason, resource limits, health probes, configuration and dependencies before choosing a fix.

Key Takeaways 🎯

  • Every field in a Kubernetes manifest serves a purpose.

  • apiVersion and kind identify the resource definition.

  • metadata provides identity and labels.

  • spec defines the desired state.

  • Containers run application processes; volumes and mounts provide files or storage.

  • Scheduling rules affect where Pods can run.

  • Security contexts help control runtime privileges.

  • Init containers complete preparation before application containers start.

  • A valid manifest does not guarantee a healthy application.

  • Production troubleshooting should be evidence-driven and systematic.

Kubernetes YAML becomes much easier when you stop treating it as a block of syntax and start seeing it as a declaration of how your application should run.

Learn what each field controls, understand how Kubernetes acts on it, and practise troubleshooting the failure modes. That is how you move from copying manifests to engineering reliable platforms. ☸️


Hashtags

#Kubernetes #KubernetesYAML #DevOps #DevOpsEngineer #AWS #EKS #Docker #CloudNative #PlatformEngineering #Terraform #CICD #Containerization #KubernetesInterview #DevOpsInterview #SRE #CloudComputing

Follow Me

If you enjoyed this article and would like more practical DevOps, Cloud, Kubernetes, AWS, Terraform, CI/CD, and Software Engineering content, feel free to connect with me on LinkedIn.

LinkedIn: https://www.linkedin.com/in/arvindverma021/

Arvind Verma is free today. But if you enjoyed this post, you can tell Arvind Verma that their writing is valuable by pledging a future subscription. You won't be charged unless they enable payments.

Pledge your support

© 2026 Arvind Verma
548 Market Street PMB 72296, San Francisco, CA 94104