Kubernetes Pod Mastery Revision&Nbsp;
# KUBERNETES POD MASTERY — CKA REVISION NOTES
GOAL:
Master Pod YAML, container configuration, volumes, Downward API, probes, resources, security, lifecycle, networking, and troubleshooting.
==================================================
1. BASIC POD STRUCTURE
==================================================
apiVersion: v1
kind: Pod
metadata:
name: mypod
namespace: pod-mastery
labels:
app: demo
spec:
restartPolicy: Always
containers:
- name: nginx
image: nginx:1.27
ports:
- containerPort: 80
IMPORTANT FIELDS:
apiVersion: API version
kind: Resource type
metadata: Name, namespace, labels, annotations
spec: Desired configuration
status: Actual observed state
FIELDS UNDER SPEC:
containers, initContainers, volumes, restartPolicy,
securityContext, nodeSelector, affinity, tolerations,
dnsPolicy, serviceAccountName, terminationGracePeriodSeconds.
FIELDS UNDER CONTAINER:
image, command, args, env, envFrom, ports, resources,
volumeMounts, probes, lifecycle, securityContext,
workingDir, imagePullPolicy.
COMMANDS:
kubectl apply -f pod.yaml
kubectl get pods -n pod-mastery -o wide
kubectl describe pod mypod -n pod-mastery
kubectl get pod mypod -n pod-mastery -o yaml
kubectl delete pod mypod -n pod-mastery
FIELD DISCOVERY:
kubectl explain pod.spec
kubectl explain pod.spec.containers
kubectl explain pod.spec.volumes
kubectl explain pod.spec.containers.env
kubectl explain pod.spec.containers.resources
==================================================
2. LABELS, SELECTORS AND ANNOTATIONS
==================================================
metadata:
labels:
app: payment
tier: backend
annotations:
description: Payment application
kubectl get pods --show-labels
kubectl get pods -l app=payment
kubectl label pod mypod environment=dev
kubectl annotate pod mypod owner=platform-team
Labels identify and select resources.
Annotations store additional metadata.
==================================================
3. COMMAND AND ARGS
==================================================
containers:
- name: worker
image: busybox:1.36
command: ["/bin/sh", "-c"]
args:
- 'echo "Starting"; sleep 3600'
command overrides the image entrypoint.
args overrides the default command arguments.
Shell syntax requires a shell such as /bin/sh -c.
==================================================
4. ENVIRONMENT VARIABLES
==================================================
Direct environment variable:
env:
- name: APP_ENV
value: production
ConfigMap envFrom:
envFrom:
- configMapRef:
name: app-config
One ConfigMap key:
env:
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: database-host
Secret key:
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
Create resources:
kubectl create configmap app-config --from-literal=APP_ENV=production
kubectl create secret generic db-secret --from-literal=password=example-password
Environment variables do not automatically update when the referenced ConfigMap or Secret changes.
==================================================
5. DOWNWARD API: FIELDREF AND RESOURCEFIELDREF
==================================================
fieldRef exposes Pod metadata or fields.
env:
- name: MY_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: MY_NODE
valueFrom:
fieldRef:
fieldPath: spec.nodeName
Other useful fields:
metadata.name
metadata.labels
metadata.annotations
spec.serviceAccountName
resourceFieldRef exposes a container resource request or limit.
containers:
- name: app
image: busybox:1.36
command: ["/bin/sh", "-c", "sleep 3600"]
resources:
limits:
memory: 200Mi
env:
- name: MEMORY_LIMIT
valueFrom:
resourceFieldRef:
containerName: app
resource: limits.memory
Downward API volume:
volumes:
- name: pod-info
downwardAPI:
items:
- path: pod-name
fieldRef:
fieldPath: metadata.name
- path: pod-namespace
fieldRef:
fieldPath: metadata.namespace
Mount it:
volumeMounts:
- name: pod-info
mountPath: /etc/pod-info
readOnly: true
Read:
kubectl exec mypod -- cat /etc/pod-info/pod-name
Remember:
fieldRef = Pod fields.
resourceFieldRef = container resource requests or limits.
==================================================
6. IMAGE SETTINGS, PORTS AND WORKING DIRECTORY
==================================================
containers:
- name: app
image: nginx:1.27
imagePullPolicy: IfNotPresent
workingDir: /tmp
ports:
- name: http
containerPort: 8080
protocol: TCP
Image pull policies:
Always: resolve/pull image when starting.
IfNotPresent: use a cached image when available.
Never: do not pull an image.
containerPort documents the container port; it does not expose the Pod externally.
Private registry example:
spec:
imagePullSecrets:
- name: registry-credentials
containers:
- name: app
image: registry.example.com/team/app:v1
The imagePullSecret must exist in the Pod namespace.
==================================================
7. MULTI-CONTAINER PODS, INIT CONTAINERS AND SIDECARS
==================================================
Containers in a Pod share the network namespace and Pod IP.
They can communicate through localhost.
They do not automatically share their filesystems.
Init container example:
spec:
initContainers:
- name: init
image: busybox:1.36
command: ["/bin/sh", "-c", "echo initialized > /shared/init.txt"]
volumeMounts:
- name: shared-data
mountPath: /shared
containers:
- name: app
image: busybox:1.36
command: ["/bin/sh", "-c", "cat /shared/init.txt; sleep 3600"]
volumeMounts:
- name: shared-data
mountPath: /shared
volumes:
- name: shared-data
emptyDir: {}
An init container must complete successfully before ordinary app containers start.
Native sidecar example:
initContainers:
- name: helper
image: busybox:1.36
restartPolicy: Always
command: ["/bin/sh", "-c", "while true; do sleep 10; done"]
Native sidecars are restartable init containers. Confirm cluster version and feature support.
==================================================
8. POD VOLUMES
==================================================
Volume types:
emptyDir: Temporary Pod-scoped storage.
hostPath: Mount a node filesystem path.
configMap: Configuration files.
secret: Sensitive configuration files.
persistentVolumeClaim: Persistent storage claim.
projected: Combine multiple volume sources.
downwardAPI: Expose Pod metadata as files.
A. EMPTYDIR
volumes:
- name: shared
emptyDir: {}
Mount into each container:
volumeMounts:
- name: shared
mountPath: /shared
Test shared storage:
kubectl exec mypod -c writer -- sh -c 'echo hello > /shared/test.txt'
kubectl exec mypod -c reader -- cat /shared/test.txt
emptyDir survives a container restart within the same Pod but is lost when the Pod is removed.
B. HOSTPATH
volumes:
- name: node-data
hostPath:
path: /data/app
type: DirectoryOrCreate
hostPath depends on the node and has security risks.
C. CONFIGMAP AND SECRET VOLUMES
volumes:
- name: config-files
configMap:
name: app-config
- name: secret-files
secret:
secretName: db-secret
Mount:
volumeMounts:
- name: config-files
mountPath: /etc/app-config
readOnly: true
- name: secret-files
mountPath: /etc/app-secret
readOnly: true
Keys generally become files in the mount directory.
D. SUBPATH
volumeMounts:
- name: config-files
mountPath: /etc/app/settings.conf
subPath: settings.conf
subPath mounts a specific file or directory.
subPath mounts do not receive normal projected ConfigMap/Secret updates.
E. PROJECTED VOLUME
volumes:
- name: combined-config
projected:
sources:
- configMap:
name: app-config
- secret:
name: db-secret
- downwardAPI:
items:
- path: pod-name
fieldRef:
fieldPath: metadata.name
Projected volumes combine multiple sources into one directory.
F. PERSISTENT VOLUME AND PVC
PVC example:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: app-pvc
namespace: pod-mastery
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
This requires a suitable StorageClass/default provisioner or a matching pre-created PV.
Mount the PVC:
spec:
containers:
- name: app
image: busybox:1.36
command: ["/bin/sh", "-c", "echo persistent > /data/test.txt; sleep 3600"]
volumeMounts:
- name: app-storage
mountPath: /data
volumes:
- name: app-storage
persistentVolumeClaim:
claimName: app-pvc
Check:
kubectl get pv
kubectl get pvc -n pod-mastery
kubectl describe pvc app-pvc -n pod-mastery
emptyDir belongs to the Pod lifetime.
PVC storage can persist beyond an individual Pod, depending on the storage backend and reclaim configuration.
==================================================
9. PROBES
==================================================
Startup probe: Determines whether startup has completed.
Readiness probe: Determines whether the Pod should receive traffic.
Liveness probe: Detects a container that should be restarted.
Example:
containers:
- name: app
image: nginx:1.27
ports:
- containerPort: 80
startupProbe:
httpGet:
path: /
port: 80
periodSeconds: 5
failureThreshold: 30
readinessProbe:
httpGet:
path: /
port: 80
periodSeconds: 5
livenessProbe:
httpGet:
path: /
port: 80
periodSeconds: 10
Probe handlers:
httpGet
tcpSocket
exec
grpc, when supported
Exec probe example:
readinessProbe:
exec:
command: ["/bin/sh", "-c", "test -f /tmp/ready"]
periodSeconds: 5
Readiness failure marks the Pod not ready.
Liveness failure can restart the container.
Startup failure can restart the container after the threshold is reached.
Startup success enables the other probes.
==================================================
10. RESOURCES AND QOS
==================================================
resources:
requests:
cpu: 100m
memory: 100Mi
limits:
cpu: 200m
memory: 200Mi
100m CPU = 0.1 CPU core.
CPU limits can cause throttling.
Memory limit exceedance can cause OOMKilled.
QoS classes:
Guaranteed: Every container has CPU and memory requests equal to limits.
Burstable: Some resource requests/limits exist but Guaranteed criteria are not met.
BestEffort: No CPU or memory requests or limits for any container.
Check:
kubectl describe pod mypod
kubectl get pod mypod -o jsonpath='{.status.qosClass}{"
"}'
Ephemeral storage:
resources:
requests:
ephemeral-storage: 100Mi
limits:
ephemeral-storage: 500Mi
Node disk pressure can lead to Pod eviction.
==================================================
11. SECURITY CONTEXT
==================================================
Pod-level security:
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 2000
Container-level security:
containers:
- name: app
image: nginxinc/nginx-unprivileged
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
seccompProfile:
type: RuntimeDefault
Important:
runAsUser: Process UID.
runAsGroup: Primary process GID.
runAsNonRoot: Require non-root execution.
fsGroup: Group-related access for supported volumes.
allowPrivilegeEscalation: Controls privilege escalation.
readOnlyRootFilesystem: Makes the container root filesystem read-only.
capabilities: Controls Linux capabilities.
seccompProfile: Restricts system calls.
Read-only filesystems may require writable temporary volumes.
Volume permissions must be compatible with the chosen UID/GID.
POD SECURITY STANDARDS:
Privileged: Few restrictions.
Baseline: Prevents known privilege-escalation patterns.
Restricted: Stronger security requirements.
POD SECURITY ADMISSION:
enforce: Reject violating Pods.
audit: Record violations.
warn: Warn about violations.
Example:
kubectl label namespace pod-mastery pod-security.kubernetes.io/warn=restricted
==================================================
12. LIFECYCLE AND GRACEFUL TERMINATION
==================================================
containers:
- name: app
image: nginx:1.27
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo started"]
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 5"]
terminationGracePeriodSeconds: 30
postStart runs after container creation but is not guaranteed to finish before the entrypoint starts.
preStop runs during termination and consumes the grace period.
Processes should handle termination signals properly.
activeDeadlineSeconds limits the total active lifetime of a Pod.
==================================================
13. RESTART POLICIES AND TROUBLESHOOTING
==================================================
restartPolicy values:
Always: Restart exited containers; default.
OnFailure: Restart containers that exit unsuccessfully.
Never: Do not restart exited containers.
Common symptoms:
Pending:
Check scheduling events, resource requests and PVC binding.
ErrImagePull/ImagePullBackOff:
Check image name, registry connectivity and credentials.
CrashLoopBackOff:
Check logs, exit code, command and probes.
CreateContainerConfigError:
Check ConfigMaps, Secrets and referenced keys.
OOMKilled:
Check memory limits and application memory usage.
Running but not Ready:
Check readiness probe and application listener.
Evicted:
Check node memory, disk and ephemeral-storage pressure.
Commands:
kubectl get pods -o wide
kubectl describe pod mypod
kubectl logs mypod -c app
kubectl logs mypod -c app --previous
kubectl exec mypod -c app -- sh
kubectl get events --sort-by=.metadata.creationTimestamp
For multi-container Pods, use -c to select the container.
--previous retrieves logs from the previous container instance.
==================================================
14. DNS, HOSTNAME AND NETWORKING
==================================================
spec:
hostname: app-host
subdomain: app-headless
dnsPolicy: ClusterFirst
DNS policies:
ClusterFirst: Cluster DNS; normal default.
Default: Inherit node DNS settings.
ClusterFirstWithHostNet: Cluster DNS behavior with host networking.
None: Use explicit DNS configuration.
Other fields:
spec:
hostNetwork: false
hostPID: false
hostIPC: false
hostAliases:
- ip: 192.0.2.10
hostnames:
- internal.example
Containers in a Pod share a network namespace, Pod IP and port space.
hostNetwork, hostPID and hostIPC can expose the Pod to host-level resources.
==================================================
15. SERVICE ACCOUNTS
==================================================
spec:
serviceAccountName: app-service-account
automountServiceAccountToken: false
Create:
kubectl create serviceaccount app-service-account -n pod-mastery
kubectl get serviceaccount -n pod-mastery
ServiceAccount provides identity, not permissions by itself.
RBAC controls permissions.
Disable automatic token mounting if the application does not need API access.
==================================================
16. SCHEDULING-RELATED POD FIELDS
==================================================
nodeSelector:
spec:
nodeSelector:
kubernetes.io/hostname: workernode2
Toleration:
spec:
tolerations:
- key: dedicated
operator: Equal
value: app
effect: NoSchedule
Other fields to recognize:
affinity
anti-affinity
topologySpreadConstraints
priorityClassName
runtimeClassName
nodeName
A toleration permits matching taints but does not guarantee scheduling onto a node.
==================================================
17. STATIC PODS AND KUBELET
==================================================
Common kubeadm configuration:
staticPodPath: /etc/kubernetes/manifests
Commands:
systemctl status kubelet
systemctl cat kubelet
cat /var/lib/kubelet/config.yaml
ls -l /etc/kubernetes/manifests/
A Static Pod is managed directly by kubelet from a local manifest.
Many kubeadm control-plane components run as Static Pods.
The path is installation-specific.
==================================================
18. TROUBLESHOOTING WORKFLOW
==================================================
Step 1:
kubectl get pod mypod -o wide
Step 2:
kubectl describe pod mypod
Step 3:
kubectl logs mypod -c app
kubectl logs mypod -c app --previous
Step 4:
kubectl get pod mypod -o yaml
kubectl explain pod.spec.containers
Check:
Field spelling and nesting.
Image and pull credentials.
ConfigMap/Secret names and keys.
Volume definitions and mounts.
Probe configuration.
Resource requests and limits.
Security context and file permissions.
Events and container exit codes.
==================================================
19. ULTIMATEPOD PRACTICE ALREADY COMPLETED
==================================================
Your integrated Pod included:
- nginx-unprivileged main container.
- BusyBox sidecar.
- ConfigMap envFrom.
- ConfigMap volume.
- Shared emptyDir.
- HTTP readiness and liveness probes.
- Exec probes for the sidecar.
- CPU/memory requests and limits.
- Pod securityContext with UID 1000, GID 1000 and fsGroup.
- allowPrivilegeEscalation: false.
Observed result:
Pod Running, 2/2 Ready, Guaranteed QoS.
ConfigMap-mounted APP_ENV file contained production.
Lessons:
Use ls to inspect directories and cat to read files.
Container filesystems are separate unless shared volumes are mounted.
A file under sidecar /tmp is not automatically visible to the main container.
Use a shared volume when containers need to exchange files.
==================================================
20. FINAL COMMAND CHEAT SHEET
==================================================
List Pods:
kubectl get pods -o wide
Inspect Pod:
kubectl describe pod mypod
View YAML:
kubectl get pod mypod -o yaml
Container logs:
kubectl logs mypod -c app
Previous logs:
kubectl logs mypod -c app --previous
Enter container:
kubectl exec -it mypod -c app -- sh
Inspect fields:
kubectl explain pod.spec.containers
ConfigMaps and Secrets:
kubectl get configmap,secret
Storage:
kubectl get pv,pvc
Events:
kubectl get events --sort-by=.metadata.creationTimestamp
Client-side dry run:
kubectl apply --dry-run=client -f pod.yaml
Generate Pod YAML:
kubectl run testpod --image=nginx --dry-run=client -o yaml
==================================================
21. HOW TO MASTER THE 60 PRACTICAL QUESTIONS
==================================================
1. Try writing YAML from memory.
2. If stuck, consult kubectl explain or official Kubernetes documentation.
3. Use AI to understand a field or correct an error, not just copy a solution.
4. Apply the manifest and verify the actual behavior.
5. Inspect events, logs, status and generated YAML.
6. Record recurring mistakes and repeat those questions.
7. Practise combining Downward API, PVCs, projected volumes, init containers, sidecars, probes and security settings.
FINAL CKA RULE:
Understand what each field does, where it belongs, how to find it and how to verify its effect. You do not need to memorize every field perfectly before practising.