0
0
KubernetesHow-ToBeginner · 3 min read

How to Create a Kubernetes Pod Using YAML

To create a pod using yaml, write a YAML file defining the pod's metadata and container specs, then run kubectl apply -f filename.yaml. This command tells Kubernetes to create the pod based on your YAML configuration.
📐

Syntax

A pod YAML file has three main parts: apiVersion, kind, and metadata to identify the pod, plus spec which describes the containers inside the pod.

  • apiVersion: Kubernetes API version, usually v1 for pods.
  • kind: The resource type, here it is Pod.
  • metadata: Information like the pod's name.
  • spec: Defines the containers, their images, and ports.
yaml
apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: nginx:1.23
    ports:
    - containerPort: 80
💻

Example

This example creates a pod named example-pod running an nginx container on port 80. After saving this YAML to pod.yaml, you run kubectl apply -f pod.yaml to create the pod.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: nginx-container
    image: nginx:1.23
    ports:
    - containerPort: 80
Output
pod/example-pod created
⚠️

Common Pitfalls

Common mistakes when creating pods with YAML include:

  • Missing or incorrect apiVersion or kind.
  • Indentation errors in YAML causing parsing failures.
  • Forgetting to specify container name or image.
  • Using kubectl create -f repeatedly without deleting old pods, causing conflicts.

Always validate YAML syntax and use kubectl apply -f to update resources safely.

yaml
Wrong YAML example:
apiVersion: v1
kind: Pod
metadata:
  name: bad-pod
spec:
  containers:
  - name: bad-container
    image: nginx

Correct YAML example:
apiVersion: v1
kind: Pod
metadata:
  name: good-pod
spec:
  containers:
  - name: good-container
    image: nginx
📊

Quick Reference

FieldDescriptionExample
apiVersionKubernetes API versionv1
kindResource typePod
metadata.namePod nameexample-pod
spec.containers[].nameContainer namenginx-container
spec.containers[].imageContainer imagenginx:1.23
spec.containers[].ports[].containerPortPort exposed by container80

Key Takeaways

Write a YAML file with apiVersion, kind, metadata, and spec to define your pod.
Use kubectl apply -f filename.yaml to create or update the pod.
Check YAML indentation carefully to avoid syntax errors.
Always specify container name and image inside spec.containers.
Use kubectl get pods to verify your pod is running after creation.