Kubernetes Pods: A Hands-on Guide

In this blog, I document my experience working with Kubernetes pods, covering imperative pod creation, YAML generation, and debugging errors. If you're new to Kubernetes or looking to solidify your basics, this is for you. Let's dive in!

Task 1: Creating a Pod Imperatively

To create a pod using the imperative command with Nginx as the image, run:

kubectl run nginx --image=nginx --restart=Never
  • The --restart=Never flag ensures it creates a pod and not a deployment.

  • Verify the pod:

      kubectl get pods
    

Task 2: Generating YAML and Creating a New Pod

After creating the pod, generate its YAML file:

kubectl get pod nginx -o yaml > nginx.yaml

Update the YAML file to change the pod name to nginx-new:

apiVersion: v1
kind: Pod
metadata:
  name: nginx-new
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx

Create the new pod using the modified YAML:

kubectl apply -f nginx.yaml

Verify:

kubectl get pods

Task 3: Debugging and Fixing Errors

Given the following faulty YAML:

apiVersion: v1
kind: Pod
metadata:
  labels:
    app: test
  name: redis
spec:
  containers:
  - image: rediss
    name: redis

Identifying the Issue

When applying the file:

kubectl apply -f redis.yaml

The following error occurs:

Failed to pull image "rediss": rpc error: code = NotFound desc = failed to resolve image "docker.io/library/rediss"

Fixing the Issue

The issue is a typo in the image name. The correct image should be redis:

apiVersion: v1
kind: Pod
metadata:
  labels:
    app: test
  name: redis
spec:
  containers:
  - image: redis
    name: redis

Apply the corrected YAML:

kubectl apply -f redis.yaml

Verify:

kubectl get pods

Learnings & Key Takeaways

  1. Imperative vs Declarative: Imperative commands are quick for one-off tasks, but YAML is better for managing Kubernetes resources long-term.

  2. YAML Manipulation: Generating YAML from existing resources helps avoid syntax errors.

  3. Troubleshooting Tips:

    • Check image names carefully.

    • Use kubectl describe pod <pod-name> to inspect errors.

    • Leverage kubectl logs <pod-name> for container logs.

    • Run kubectl get events to see cluster-level issues.

Acknowledgments

Tagging @PiyushSachdeva and the CloudOps Community for insights and discussions.