Lab 3.1 - Creating and Managing Pods
Objectives
By the end of this lab, you will be able to:
- Create Pods with YAML
- Manage the Pod lifecycle
- Use labels and selectors
- Inspect Pods
Prerequisites
- Functioning Kubernetes cluster
- kubectl installed and configured
Exercise 1: Create a Simple Pod
Step 1: Create the YAML file
Create pod-simple.yaml:
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
env: dev
spec:
containers:
- name: nginx
image: nginx:1.20
ports:
- containerPort: 80
Step 2: Create the Pod
kubectl apply -f pod-simple.yaml
Step 3: Verify
# View the Pod
kubectl get pods
# Details
kubectl describe pod nginx-pod
# Logs
kubectl logs nginx-pod
Exercise 2: Pod with Environment Variables
Create pod-env.yaml:
apiVersion: v1
kind: Pod
metadata:
name: env-pod
spec:
containers:
- name: busybox
image: busybox
command: ['sh', '-c', 'echo $MESSAGE && sleep 3600']
env:
- name: MESSAGE
value: "Hello from Kubernetes!"
Apply and check the logs.
Exercise 3: Multi-Container Pod
Create pod-multi.yaml:
apiVersion: v1
kind: Pod
metadata:
name: multi-pod
spec:
containers:
- name: nginx
image: nginx:1.20
- name: busybox
image: busybox
command: ['sh', '-c', 'while true; do echo $(date); sleep 5; done']
Test the communication between containers.
Exercise 4: Labels and Selectors
Step 1: Create multiple Pods with labels
kubectl run pod1 --image=nginx:1.20 --labels=app=web,env=prod
kubectl run pod2 --image=nginx:1.20 --labels=app=web,env=prod
kubectl run pod3 --image=nginx:1.20 --labels=app=api,env=dev
Step 2: Filter with labels
# Pods with app=web
kubectl get pods -l app=web
# Pods with app=web AND env=prod
kubectl get pods -l app=web,env=prod
# Pods without env=dev
kubectl get pods -l 'env!=dev'
Exercise 5: Lifecycle
Step 1: Observe the phases
# Create a Pod
kubectl run test-pod --image=nginx:1.20
# Observe the phases
kubectl get pod test-pod -w
# View events
kubectl describe pod test-pod
Step 2: Test the restart
Create a Pod that crashes:
apiVersion: v1
kind: Pod
metadata:
name: crash-pod
spec:
restartPolicy: Always
containers:
- name: busybox
image: busybox
command: ['sh', '-c', 'exit 1']
Observe the automatic restart.
Cleanup
# Delete all created Pods
kubectl delete pod nginx-pod env-pod multi-pod pod1 pod2 pod3 test-pod crash-pod
Reflection Questions
- What is the difference between a single-container and multi-container Pod?
- How do containers in a Pod communicate?
- Why use labels?
- What happens if a container crashes?
Next Steps
Lab 3.2: Deploying with ReplicaSets
Chapter 3.5: ReplicaSets
Lab created: December 2024