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
v1for 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: 80Example
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: 80Output
pod/my-pod created
Common Pitfalls
Common mistakes when creating pods include:
- Using incorrect indentation in YAML, which causes errors.
- Forgetting to specify
containerPortif the container listens on a port. - Using an image name that does not exist or is misspelled.
- Not running
kubectl apply -fin 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: nginxQuick Reference
| Field | Description |
|---|---|
| apiVersion | Kubernetes API version, usually 'v1' for pods |
| kind | Resource type, here 'Pod' |
| metadata.name | Name of the pod |
| spec.containers | List of containers in the pod |
| containers[].name | Name of the container |
| containers[].image | Container image to run |
| containers[].ports.containerPort | Port 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'.