Appearance
Pods and Workload Types
334. What is a Pod, and why is it the basic deployable unit in Kubernetes?
The short answer
A pod is a group of one or more containers that always run together on the same node, share one network identity, meaning one IP address and one set of ports, and can share storage volumes. Kubernetes schedules, starts, stops and replaces whole pods, never single containers. That is because some processes genuinely belong together, such as an app and a helper that must talk over localhost or read the same files, and the pod gives them one shared, managed home.
What the containers in a pod share:
- The network namespace: one IP address, one set of ports. Containers in a pod reach each other on
localhost, and two containers in one pod cannot both listen on port 8080. - Volumes: any volume declared in the pod can be mounted into several of its containers.
- The node: they are always scheduled together.
- The life cycle: they are created and deleted together.
What they do not share by default: their filesystems, apart from shared volumes, and their process lists, unless shareProcessNamespace: true is set.
How the sharing works. Each pod starts with a tiny sandbox container, often called the pause container, whose only job is to hold the pod's network namespace open. The app containers then join that namespace. If an app container restarts, the pod keeps its IP address, because the sandbox never stopped.
Why pods, and not just containers, are the unit:
- Helpers that must be near the app, such as a proxy or a log shipper, need to share its network and files. A pod gives them that, as one scheduling decision (question 335).
- One identity for traffic. A Service sends traffic to a pod's IP, whatever containers are inside.
- Simple scheduling. The scheduler finds a node for the whole pod's resource needs at once.
A pod is disposable. Pods are not moved or repaired. When a node dies, its pods are gone, and controllers create new pods, with new names and new IP addresses, elsewhere. Anything that must survive goes outside the pod: data on volumes, traffic routing through Services.
335. Can a Pod contain multiple containers, and when should containers share one Pod?
The short answer
Yes. Put containers in one pod only when they are tightly coupled. They must run on the same machine, start and stop together, and share the network or files. Examples are an app plus a log shipper that reads its log files, or an app plus a local proxy. Do not put independent components, such as a web app and its database, in one pod, because they need to scale, update and fail separately.
localhost, and they share the logs volume. They are scheduled, started and removed together.Common patterns:
| Pattern | Helper container's job | Example |
|---|---|---|
| Sidecar | Adds a feature next to the app | Log shipper, a service mesh proxy, a file syncer |
| Adapter | Translates the app's output | Converts the app's metrics into Prometheus format |
| Ambassador | Proxies the app's outbound calls | A local proxy to a database or an outside API |
| Init container | Runs once before the app starts | Waits for a dependency, prepares files (question 355) |
Keep them in separate pods when:
- They scale differently. Three copies of the web app should not mean three databases.
- They update separately. A new web release should not restart the database.
- They fail separately. A crashed web container should not take a cache down with it.
- They do not need to share a machine. Over the network is fine, through a Service.
A useful test: "would this helper make sense without this exact app, on this exact machine?" If not, it belongs in the pod. If yes, it probably deserves its own.
Native sidecars. Since Kubernetes 1.33, sidecars can be declared as init containers with restartPolicy: Always. They then start before the app and stop after it, which fixes old ordering problems, such as a log shipper exiting before the app finished writing (question 355).
336. What resources can be created directly, and why are standalone Pods usually not the normal production deployment method?
The short answer
Almost every kind of object can be created directly, including bare pods. But a pod created on its own has no controller looking after it. If its node fails, or it is evicted, it is simply gone and nothing creates a replacement. You cannot scale it, roll out a new version safely, or roll back. In production, pods are always created by a controller, such as a Deployment, StatefulSet, DaemonSet or Job, which keeps them running and manages their changes.
bash
kubectl run debug --image=busybox --rm -it -- sh # a standalone pod: fine for a quick debugging sessionWhat a standalone pod lacks:
| Need | Standalone pod | Pod managed by a Deployment |
|---|---|---|
| Replaced if the node dies | No | Yes |
| Replaced if evicted | No | Yes |
| More copies | Create each by hand | Change replicas |
| New version | Delete and recreate, with downtime | Rolling update |
| Roll back | Recreate the old one by hand | kubectl rollout undo |
Note on restarts: the kubelet does restart a standalone pod's crashed containers, on the same node, according to its restart policy. What it cannot do is recreate the pod somewhere else when the pod itself is lost.
What is usually created directly: the controllers themselves, Services, ConfigMaps, Secrets, persistent volume claims, network policies, roles, and so on, all declared in files and applied (question 324).
When bare pods are fine: short debugging sessions, one-off experiments, and tests of a pod specification before wrapping it in a Deployment.
337. What is a ReplicaSet, and how does it maintain a desired number of Pod replicas?
The short answer
A ReplicaSet keeps a set number of identical pods running. It has a desired count, a label selector that says which pods count as its own, and a pod template for making new ones. Its controller constantly counts the matching pods: if there are too few, it creates more from the template; if there are too many, it deletes some. You rarely create ReplicaSets yourself, because Deployments create and manage them for you.
yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: checkout-api-7d9f
spec:
replicas: 3 # (1)
selector:
matchLabels: { app: checkout-api, pod-template-hash: 7d9f } # (2)
template: # (3)
metadata:
labels: { app: checkout-api, pod-template-hash: 7d9f }
spec:
containers:
- name: api
image: myacr.azurecr.io/shop/checkout-api@sha256:41c9b0e8...- The desired count.
- Which pods belong to it. The
pod-template-hashlabel is added by the Deployment, so each ReplicaSet only ever counts its own pods, even when an old and a new one exist together during a rollout. - The recipe for new pods.
The loop, in practice:
- A node dies, taking one pod with it. The ReplicaSet now counts 2 of 3. It creates one new pod from the template, and the scheduler places it on a healthy node.
- Someone manually starts an extra pod with exactly matching labels. The ReplicaSet counts 4 of 3, and deletes one.
- You change
replicasto 5. It creates two more.
Adopting pods. A ReplicaSet even takes ownership of existing pods that match its selector and have no owner. That is one reason labels must be specific: an overly broad selector can capture pods it was never meant to manage (question 326).
338. What is a Deployment, and what does it manage for a stateless application?
The short answer
A Deployment manages a stateless application declaratively. You state the pod template and the number of replicas, and it creates a ReplicaSet to run them. When you change the template, for example the image, it creates a new ReplicaSet and gradually moves pods from the old one to the new one, a rolling update. It keeps a history of old ReplicaSets so you can roll back, and it lets you scale, pause and resume rollouts.
"Stateless" means any pod is as good as any other. None of them holds data that the others lack. Requests can go to any copy, and any copy can be replaced at any time. Web front ends and most APIs are stateless, because their data lives in a database elsewhere.
What a Deployment manages:
- ReplicaSets: one per version of the pod template.
- Rolling updates: changing the template starts a gradual replacement, limited by
maxSurgeandmaxUnavailable(question 351). - Rollback: old ReplicaSets are kept, scaled to zero, as revisions. By default it keeps 10, set by
revisionHistoryLimit(question 352). - Scaling:
replicas, changed by hand or by an autoscaler (question 397). - Progress tracking: if a rollout makes no progress within
progressDeadlineSeconds, 600 seconds by default, its status reportsProgressDeadlineExceeded(question 428). - Pause and resume, to batch several template changes into one rollout.
bash
kubectl set image deploy/checkout-api api=myacr.azurecr.io/shop/checkout-api@sha256:9e07... # starts a rollout
kubectl rollout status deploy/checkout-api # wait for it
kubectl get rs -l app=checkout-api # old and new ReplicaSetsNAME DESIRED CURRENT READY AGE
checkout-api-7d9f 0 0 0 2d
checkout-api-5c8b 3 3 3 40sThe old ReplicaSet is still there at zero, ready to be scaled back up by a rollback.
339. What is the difference between a Pod, ReplicaSet, and Deployment?
The short answer
They are three layers, each managing the one below. A pod runs containers. A ReplicaSet keeps a fixed number of identical pods running. A Deployment manages ReplicaSets, one per version, to provide rolling updates and rollbacks. In practice you write Deployments, and Kubernetes creates the ReplicaSets and pods for you.
| Pod | ReplicaSet | Deployment | |
|---|---|---|---|
| Manages | Containers | Pods | ReplicaSets |
| Keeps a count of copies | No | Yes | Through its ReplicaSets |
| Rolling updates | No | No | Yes |
| Rollback history | No | No | Yes |
| You normally write it | No | No | Yes |
A good way to explain it: the pod is a worker. The ReplicaSet is a supervisor who keeps exactly three workers on shift. The Deployment is the manager. When the job changes, the manager hires a new supervisor with retrained workers, and gradually sends the old shift home. The manager keeps the old supervisor's phone number, in case the change goes badly.
340. What is a StatefulSet, and when is stable identity or ordered storage useful?
The short answer
A StatefulSet runs pods that each need their own lasting identity. Each pod gets a fixed name with a number, such as orders-db-0 and orders-db-1, a fixed DNS name through a headless Service, and its own persistent volume that follows it if it is rescheduled. Pods are created, updated and removed in order, one at a time. That suits software where each copy has its own role or data, such as databases, Kafka or ZooKeeper.
yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: orders-db
spec:
serviceName: orders-db # (1)
replicas: 3
selector:
matchLabels: { app: orders-db }
template:
metadata:
labels: { app: orders-db }
spec:
containers:
- name: postgres
image: postgres:16.4
volumeMounts:
- { name: data, mountPath: /var/lib/postgresql/data }
volumeClaimTemplates: # (2)
- metadata: { name: data }
spec:
accessModes: [ReadWriteOnce]
resources: { requests: { storage: 100Gi } }- The headless Service that gives each pod its own DNS name, such as
orders-db-0.orders-db.shop-prod.svc.cluster.local(question 489). - A template for volume claims. Each pod gets its own claim, named
data-orders-db-0and so on, which is kept even when the pod is deleted (question 386).
The guarantees:
- Stable names:
orders-db-0,-1,-2, never random. - Stable network identity: each pod's own DNS name, so others can say "connect to
orders-db-0, the primary". - Stable storage: each pod reattaches to its own volume, wherever it is scheduled.
- Ordered operations: by default, pod 0 must be running and ready before pod 1 starts, and scale-down removes the highest number first. Rolling updates go from the highest number down.
When to use one: software where copies have different roles or their own data: databases with a primary and replicas, Kafka brokers, ZooKeeper and etcd members, Elasticsearch nodes. When not to: stateless apps, which get nothing from the extra rules and roll out more slowly.
A StatefulSet does not make a database highly available by itself. Replication, failover and backups are the database's job, often handled by an operator (question 331).
341. What is a DaemonSet, and which workloads commonly use it?
The short answer
A DaemonSet runs one copy of a pod on every node, or on every node matching a selector. When a new node joins, it automatically gets a copy, and when a node leaves, its copy goes too. It is used for agents that must run on each machine: log collectors, monitoring agents, network plugin agents, kube-proxy, storage drivers and security agents.
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-exporter
namespace: monitoring
spec:
selector:
matchLabels: { app: node-exporter }
template:
metadata:
labels: { app: node-exporter }
spec:
tolerations:
- operator: Exists # (1)
containers:
- name: node-exporter
image: quay.io/prometheus/node-exporter:v1.8.2
ports: [{ containerPort: 9100 }]- Tolerate every taint, so the agent also runs on special nodes, such as control-plane or GPU nodes, which repel normal pods (question 394).
Typical DaemonSets:
| Workload | Why it must be on every node |
|---|---|
| Log collector, such as Fluent Bit | Reads container log files from each node's disk |
| Node metrics, such as node-exporter | Reports each machine's CPU, memory and disk |
| Network plugin agent, such as Cilium | Sets up pod networking on each node |
| kube-proxy | Writes Service rules on each node |
| Storage driver node plug-in | Mounts volumes on each node |
| Security agent | Watches activity on each machine |
Two details:
- Limit it to some nodes with a
nodeSelectoror node affinity, for example GPU drivers only on GPU nodes. - Updates roll node by node, controlled by
maxUnavailable, so a bad agent version does not break every node at the same moment.
342. What is a Job, and how does it differ from a continuously running Deployment?
The short answer
A Job runs pods until a task is finished, then stops. Success means the pod's process exited with code 0. If it fails, the Job retries, up to a limit, and you can run several pods in parallel or require a number of successful completions. A Deployment is the opposite: its pods are meant to run forever, and if one exits, even successfully, it is restarted. Use Jobs for batch work such as migrations, reports and data imports.
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: migrate-orders-2026-10-27
spec:
backoffLimit: 3 # (1)
activeDeadlineSeconds: 900 # (2)
ttlSecondsAfterFinished: 86400 # (3)
template:
spec:
restartPolicy: Never # (4)
containers:
- name: migrate
image: myacr.azurecr.io/shop/checkout-api@sha256:41c9b0e8...
command: ["node", "dist/migrate.js"]- Retry at most three times after failures. The default is six. Retries wait longer each time.
- Fail the whole Job if it has not finished within 15 minutes, whatever the retries.
- Delete the finished Job and its pods automatically after one day, so they do not pile up.
- A Job's pods must use
NeverorOnFailure, neverAlways. WithNever, each retry is a new pod, which keeps the failed pods' logs for inspection.
Running many at once:
completions: 10means the Job is done when ten pods have succeeded.parallelism: 3means at most three run at the same time.- An indexed Job,
completionMode: Indexed, gives each pod a number from 0 to 9, so each can process its own slice of the work.
| Job | Deployment | |
|---|---|---|
| Purpose | Finish a task | Keep a service running |
| Pod exits with 0 | Success, done | Restarted |
| Pod exits with an error | Retried, up to a limit | Restarted |
| Restart policy | Never or OnFailure | Always |
| Ends | Yes | No |
343. What is a CronJob, and how do you control overlapping scheduled executions?
The short answer
A CronJob creates a Job on a schedule, written in cron syntax, such as every night at 2 a.m. Sometimes the previous run is still going when the next one is due. concurrencyPolicy controls what happens then. Allow, the default, lets them overlap. Forbid skips the new run. Replace stops the old run and starts the new one. Also set a deadline for starting late, history limits, and a time zone, and make the job itself safe to run twice.
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-sales-report
spec:
schedule: "0 2 * * *" # (1)
timeZone: "Europe/London" # (2)
concurrencyPolicy: Forbid # (3)
startingDeadlineSeconds: 600 # (4)
successfulJobsHistoryLimit: 3 # (5)
failedJobsHistoryLimit: 5
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: report
image: myacr.azurecr.io/shop/reports@sha256:7c1e...
command: ["node", "dist/sales-report.js"]- At minute 0 of hour 2, every day. The five fields are minute, hour, day of month, month and day of week.
- In London time. Without this, the schedule follows the time zone of the controller manager, usually UTC.
- If last night's report is still running at 2 a.m., do not start another.
- If the CronJob could not start within 10 minutes of the scheduled time, for example because the control plane was down, skip this run instead of starting it late.
- Keep the last three successful and five failed Jobs, so you can read their logs.
concurrencyPolicy | If the previous run is still going |
|---|---|
Allow | Start another anyway; they run in parallel |
Forbid | Skip this run |
Replace | Stop the old run, start the new one |
Make the job itself idempotent. Kubernetes can occasionally create a Job twice for one schedule, or not at all, for example during control-plane problems. A report job should check "has today's report already been made?" before doing the work. A one-off misfire then costs nothing.
Pausing it: suspend: true stops new runs without deleting the CronJob, which is useful during an incident or a migration.
344. What is the difference between a Deployment, StatefulSet, DaemonSet, Job, and CronJob?
The short answer
A Deployment runs interchangeable copies of a long-running stateless service. A StatefulSet runs long-running copies that each keep their own name, address and storage. A DaemonSet runs one copy on every node. A Job runs a task until it finishes. A CronJob runs a Job on a schedule. Choose by asking: does it run forever or finish, are the copies interchangeable, and does it need to be on every node?
| Deployment | StatefulSet | DaemonSet | Job | CronJob | |
|---|---|---|---|---|---|
| Runs | Forever | Forever | Forever | Until done | Until done, on a schedule |
| Copies | N, interchangeable | N, each unique | One per node | As configured | As configured, per run |
| Pod names | Random | Fixed, numbered | Random | Random | Random |
| Own storage per pod | No | Yes | No | No | No |
| Order of start and update | Any | In order | Node by node | Not applicable | Not applicable |
| Typical use | Web apps, APIs | Databases, brokers | Agents on each node | Migrations, batches | Nightly reports, clean-ups |
A quick way to choose:
- Does it finish? Job, or CronJob if it repeats on a schedule.
- Must it run on every node? DaemonSet.
- Does each copy need its own identity or data? StatefulSet.
- Otherwise: Deployment.
345. What are the most important fields in a Pod or Deployment YAML manifest?
The short answer
At the top: apiVersion, kind and metadata with the name, namespace and labels. In the Deployment's spec: replicas, the selector, the update strategy and the pod template. In the pod template: the containers, each with its image, ports, environment, resource requests and limits, probes, volume mounts and security settings, plus the pod's volumes, service account, security context, shutdown grace period and placement rules.
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout-api
namespace: shop-prod
labels: { app.kubernetes.io/name: checkout-api }
spec:
replicas: 3
revisionHistoryLimit: 5
selector:
matchLabels: { app.kubernetes.io/name: checkout-api } # (1)
strategy:
type: RollingUpdate
rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 } # (2)
template:
metadata:
labels: { app.kubernetes.io/name: checkout-api }
spec:
serviceAccountName: checkout-api # (3)
terminationGracePeriodSeconds: 30
securityContext:
runAsNonRoot: true
seccompProfile: { type: RuntimeDefault } # (4)
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels: { app.kubernetes.io/name: checkout-api } # (5)
containers:
- name: api
image: myacr.azurecr.io/shop/checkout-api@sha256:41c9b0e8... # (6)
ports: [{ name: http, containerPort: 8080 }]
envFrom: [{ configMapRef: { name: checkout-api-config } }]
env:
- name: DB_PASSWORD
valueFrom: { secretKeyRef: { name: checkout-db, key: password } } # (7)
resources:
requests: { cpu: 250m, memory: 384Mi } # (8)
limits: { memory: 512Mi }
startupProbe:
httpGet: { path: /healthz, port: http }
failureThreshold: 30
periodSeconds: 2
readinessProbe:
httpGet: { path: /ready, port: http } # (9)
livenessProbe:
httpGet: { path: /healthz, port: http }
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: [ALL] } # (10)
volumeMounts: [{ name: tmp, mountPath: /tmp }]
volumes:
- name: tmp
emptyDir: {}- The selector must match the template's labels (question 347).
- Never drop below three ready pods during a rollout, and add up to 25% extra at a time (question 351).
- The identity the pod uses to talk to the API server or, with workload identity, to the cloud (question 416).
- Pod-wide security: refuse to start as root, use the runtime's default system call filter (question 418).
- Spread copies across availability zones (question 396).
- The image, pinned by digest (question 87).
- A setting read from a Secret (question 378).
- What the scheduler reserves, and the memory ceiling (question 389).
- Probes: start-up, readiness for traffic, liveness for restarts (question 401).
- Container-level hardening: no privilege escalation, read-only filesystem, no capabilities (question 419).
346. What do apiVersion, kind, metadata, and spec represent in a Kubernetes manifest?
The short answer
apiVersion says which API group and version defines the object, such as apps/v1. kind says what type of object it is, such as Deployment. metadata identifies the object: its name, namespace, labels and annotations. spec describes what you want the object to be. Kubernetes adds a fifth part, status, which reports what actually is.
| Field | Meaning | Example |
|---|---|---|
apiVersion | API group and version | apps/v1, v1, networking.k8s.io/v1 |
kind | The object's type | Deployment, Service, ConfigMap |
metadata | Identity and tags | name, namespace, labels, annotations |
spec | Desired state | replicas: 3, the pod template |
status | Observed state, written by Kubernetes | readyReplicas: 3 |
apiVersion in more depth. Kubernetes groups related kinds: apps holds Deployments and StatefulSets, batch holds Jobs and CronJobs, networking.k8s.io holds Ingress and NetworkPolicy. The oldest kinds, such as Pod, Service and ConfigMap, live in the core group, written as just v1. Versions move from v1alpha1 to v1beta1 to v1 as an API matures, and old beta versions are eventually removed, which matters when upgrading clusters (question 501).
metadata also has fields the system sets: uid, a unique ID; resourceVersion, which changes on every update and lets Kubernetes detect two people editing at once; creationTimestamp; generation; and ownerReferences (question 487).
Some objects have no spec. A ConfigMap has data instead, because it simply stores values and has no desired state to reach.
347. How do spec.selector and Pod-template labels need to align in a Deployment?
The short answer
The selector must match the labels in the pod template, otherwise the Deployment would create pods it does not recognise as its own, and the API server rejects it. The selector is also fixed once the Deployment exists: you cannot change it later, so changing the labels it selects on means creating a new Deployment. And no two Deployments should have overlapping selectors, or their controllers will fight over the same pods.
yaml
spec:
selector:
matchLabels:
app.kubernetes.io/name: checkout-api # (1)
template:
metadata:
labels:
app.kubernetes.io/name: checkout-api # (2)
version: "1.4" # (3)- The selector: "my pods are the ones labelled
app.kubernetes.io/name: checkout-api". - The template gives every new pod that label, so the Deployment recognises them.
- The template may carry extra labels that are not in the selector. That is fine, and useful.
If they do not match, the request is refused:
The Deployment "checkout-api" is invalid: spec.template.metadata.labels: Invalid value: map[string]string{"app":"checkout"}: `selector` does not match template `labels`If you try to change the selector later:
spec.selector: Invalid value: ...: field is immutableTo change it, create a new Deployment with the new selector, move traffic, then delete the old one.
Three rules that avoid trouble:
- Select on a stable identity label, such as the app's name, never on something that changes per release, such as a version. A version in the selector would make every release need a new Deployment.
- Keep selectors unique. Two Deployments selecting the same pods will each see the other's pods as extras and delete them, in an endless tug of war.
- Remember Services select separately. A Service's selector is its own setting. It should match the pods' labels too, or the Service will have no endpoints (question 362).