0
0
KubernetesHow-ToBeginner · 4 min read

How to Create a Pod in Kubernetes: Simple Steps

To create a pod in Kubernetes, write a YAML file defining the pod's specifications and run kubectl apply -f filename.yaml. This command tells Kubernetes to create the pod based on the YAML configuration.
📐

Syntax

A Kubernetes pod is defined using a YAML file with these main parts:

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

Example

This example creates a pod named my-pod running an nginx web server container on port 80.

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

Common Pitfalls

Common mistakes when creating pods include:

  • Using incorrect indentation in YAML, which causes errors.
  • Forgetting to specify containerPort if the container listens on a port.
  • Using an image name that does not exist or is misspelled.
  • Not running kubectl apply -f in the correct directory or with the correct file name.

Always validate your YAML with kubectl apply --dry-run=client -f filename.yaml before creating the pod.

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

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

Quick Reference

FieldDescription
apiVersionKubernetes API version, usually 'v1' for pods
kindResource type, here 'Pod'
metadata.nameName of the pod
spec.containersList of containers in the pod
containers[].nameName of the container
containers[].imageContainer image to run
containers[].ports.containerPortPort the container listens on

Key Takeaways

Create a pod by writing a YAML file and applying it with kubectl.
Ensure correct YAML indentation to avoid errors.
Specify container image and ports clearly in the pod spec.
Use kubectl apply --dry-run to validate YAML before creating pods.
Pod creation output confirms success, e.g., 'pod/my-pod created'.