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
v1for 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: 80Example
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: 80Output
pod/example-pod created
Common Pitfalls
Common mistakes when creating pods with YAML include:
- Missing or incorrect
apiVersionorkind. - Indentation errors in YAML causing parsing failures.
- Forgetting to specify container
nameorimage. - Using
kubectl create -frepeatedly 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: nginxQuick Reference
| Field | Description | Example |
|---|---|---|
| apiVersion | Kubernetes API version | v1 |
| kind | Resource type | Pod |
| metadata.name | Pod name | example-pod |
| spec.containers[].name | Container name | nginx-container |
| spec.containers[].image | Container image | nginx:1.23 |
| spec.containers[].ports[].containerPort | Port exposed by container | 80 |
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.