Pods and workloadsLesson 3 of 7
  1. Pod anatomy, not reconciled
  2. Pod lifecycle, restarts and termination, not reconciled
  3. Init containers and native sidecars, not reconciled
    1. Init containers
    2. Typical init work
    3. Native sidecars (GA 1.33)
    4. Ordering
    5. Sidecars in Jobs
    6. Resource accounting
    7. Migrating helper containers
  4. Probes: startup, readiness and liveness, not reconciled
  5. Deployments and rolling updates, not reconciled
  6. DaemonSets, not reconciled
  7. Jobs and CronJobs, not reconciled

Init containers and native sidecars

Sequence setup work with init containers, run helpers as native sidecars that start first and stop last, and let Jobs finish without a helper holding them open.

  • 22 min
  • 4 objectives
  • 7 scenes

Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.

Reconcile, in 7 scenes

Init containers

An init containerA container listed under spec.initContainers that runs to completion before the pod’s app containers start. does one job and exits. A pod can have several, and the kubelet runs them one at a time, in the order they are listed. Each must exit 0 before the next one starts, and the app containers start only after the last one has succeeded.

Before the first init container runs, the kubelet needs the pod sandbox, an IP address from the CNI plugin and every volume mounted. The PodReadyToStartContainers condition, stable in Kubernetes 1.37, reports exactly that. If one of those steps never finishes, no init container starts at all, and the pod’s events name the step that is stuck. In a pod without init containers the same stall shows as ContainerCreating, which is rarely an image problem: a failed pull shows ErrImagePull or ImagePullBackOff, and only a slow pull of a large image looks like ContainerCreating.

While the init containers run, the pod’s phase is Pending and its Initialized condition is False. The pod cannot be Ready, so no Service sends it traffic. kubectl shows progress in the STATUS column as Init:1/2, then PodInitializing while the app containers are created. The full list of conditions is PodScheduled, PodReadyToStartContainers, Initialized, ContainersReady and Ready, plus DisruptionTarget, PodResizePending and PodResizeInProgress when they apply.

What happens when an init container fails depends on the pod’s restartPolicy, which defaults to Always for every pod, whether you create it yourself or a Deployment does (and Deployments accept nothing else). Under Always or OnFailure, the kubelet retries the failing init container in place with the usual crash-loop back-off: 10 seconds, doubling to a cap of 300. The pod stays Pending, because it never finishes initializing; the same back-off on an app container would leave the pod Running. Under Never, one failed init container makes the whole pod Failed, and Failed is terminal: nothing restarts it.

An init container holds the pod until a name resolves
kubectl get pod checkout
NAME       READY   STATUS                  RESTARTS      AGE
checkout   0/2     Init:CrashLoopBackOff   2 (16s ago)   30s
kubectl get pod checkout -o jsonpath='{.status.phase}'
Pending
kubectl logs checkout -c wait-for-payments
Server:		10.96.0.10
Address:	10.96.0.10:53

** server can't find payments.default.svc.cluster.local: NXDOMAIN

** server can't find payments.default.svc.cluster.local: NXDOMAIN
kubectl create service clusterip payments --tcp=443:8443
service/payments created
kubectl wait --for=condition=Ready pod/checkout --timeout=120s
pod/checkout condition met
kubectl get pod checkout
NAME       READY   STATUS    RESTARTS   AGE
checkout   2/2     Running   0          45s

The init container looked up a Service that did not exist and exited 1. Once the Service existed, its next attempt succeeded and the rest of the pod started. While the pod was initializing, RESTARTS counted the init container’s attempts; once it was running, the column counts restarts of the sidecar and app containers instead.

Plain init containers cannot have lifecycle hooks or liveness, readiness or startup probes: their only signal is the exit code. The kubelet may also run them more than once, for example when the pod sandbox has to be recreated, so every init container must be idempotent. A script that writes into an emptyDir should expect to find its output from an earlier run already there.

Nothing limits how long the init sequence may keep retrying. The pod-level activeDeadlineSeconds covers init containers and fails the pod when the deadline passes, but it keeps counting after initialization and would kill a healthy long-running pod too. Use it on Job pods, and rely on alerts for pods stuck in Init: elsewhere.

Typical init work

Init containers are for work that must finish before the application starts, and that you would rather not bake into the application image:

  • Wait for a dependency. Loop until a Service resolves or a port answers, as wait-for-payments does above. This gates only startup; it does not notice the dependency going away later.
  • Render configuration. Fetch settings or templates and write the final file into an emptyDir that the app container mounts read-only.
  • Run a schema migration. Apply migrations before the new version starts. With several replicas, every pod runs its own init container, so the migration tool must take a lock or tolerate running concurrently.
  • Fix volume permissions. chown a volume for an app that runs as a non-root user. Check securityContext.fsGroup first: for volumes that support ownership management, the kubelet sets group ownership itself, without an extra container.

Each of these keeps tools out of the app image. The init container can carry nslookup, a migration binary or a templating tool, and the app image stays small, with fewer packages to patch.

Waiting for a dependency is better done here than in a readiness probe on every replica. The Kubernetes docs do suggest that readiness may check strict back-end dependencies, but a readiness probe that checks a database every replica shares turns one database outage into every replica going unready at once, and the Service is left with no endpoints at all.

Native sidecars (GA 1.33)

A native sidecarAn init container with restartPolicy: Always: it starts in init order, keeps running beside the app containers and stops after them. is declared as an init container with one extra field. Native sidecars have been on by default since Kubernetes 1.29 and are GA since 1.33.

apiVersion: v1
kind: Pod
metadata:
  name: checkout
  labels:
    app: checkout
spec:
  initContainers:
  - name: wait-for-payments
    image: busybox:1.37
    command: ["sh", "-c", "nslookup payments.default.svc.cluster.local"]
  - name: cache
    image: redis:8.10
    restartPolicy: Always
    ports:
    - containerPort: 6379
    startupProbe:
      tcpSocket:
        port: 6379
      periodSeconds: 2
      failureThreshold: 15
  containers:
  - name: app
    image: nginx:1.31
    ports:
    - containerPort: 80

cache is listed under initContainers, but restartPolicy: Always changes three things about it:

  • It does not have to exit. The kubelet moves on to the next init container as soon as the sidecar has started, and leaves it running for the life of the pod.
  • It is restarted whenever it stops, whatever the pod’s restartPolicy, with the same back-off as any other container.
  • It may have probes and lifecycle hooks. Any of the four probe mechanisms works: exec, httpGet, tcpSocket, or grpc, which is GA since Kubernetes 1.27. A sidecar’s readiness counts toward the pod’s Ready condition, and kubectl counts sidecars in the READY column, which is why checkout showed 2/2 above.

A sidecar shares the pod’s network namespace and can share its volumes, so the app reaches cache on localhost:6379. Changing a sidecar’s image restarts that container, not the pod.

Because a sidecar’s readiness feeds the pod’s, a sidecar that fails its readiness probe takes the whole pod out of its Services’ EndpointSlices even while the app is healthy. A failing liveness probe restarts only the sidecar. Probe a sidecar for what the app needs from it, and no more.

Ordering

A sidecar inherits the strict ordering of init containers. The kubelet starts the next entry in initContainers, or the app containers after the last entry, only once the sidecar has started. Started means its process is running and, if it has a startupProbe, the probe has succeeded. Without a startup probe, the sidecar counts as started as soon as its process is running, which can be well before it accepts connections. The startup probe on cache above holds the app back until Redis is listening.

The sidecar starts before the app
kubectl create service clusterip payments --tcp=443:8443
service/payments created
kubectl wait --for=condition=Ready pod/checkout --timeout=120s
pod/checkout condition met
kubectl get pod checkout -o jsonpath='{range .status.initContainerStatuses[*]}{.name}{"\t"}{.state.terminated.reason}{.state.running.startedAt}{"\n"}{end}{range .status.containerStatuses[*]}{.name}{"\t"}{.state.running.startedAt}{"\n"}{end}'
wait-for-payments	Completed
cache	2026-11-19T09:01:09Z
app	2026-11-19T09:01:15Z

wait-for-payments completed, cache started and passed its startup probe, and only then did the kubelet pull and start app, six seconds after cache. The order matters inside initContainers too: an init container that needs the sidecar, such as a migration that connects through a database proxy, must be listed after it, or it runs before the sidecar exists.

Shutdown runs the other way. When the pod is deleted, the kubelet sends SIGTERM to the app containers first and waits for them to stop. Only then does it stop the sidecars, in the reverse of their order in the spec, so the sidecar listed first is stopped last. A proxy listed first therefore carries the app’s in-flight requests to the end. All of this happens inside one terminationGracePeriodSeconds. If the app containers use up the grace period, the sidecars get SIGTERM and then SIGKILL almost at once, and a non-zero exit code from a sidecar during pod termination is normal.

Sidecars in Jobs

A Job’s pod succeeds when its containers have finished. A helper declared as a second entry under containers is one of those containers, and a log shipper that loops forever never finishes. A native sidecar is not counted: once every regular container has terminated, the kubelet stops the sidecars and the pod completes.

apiVersion: batch/v1
kind: Job
metadata:
  name: report-native
spec:
  backoffLimit: 2
  template:
    spec:
      restartPolicy: Never
      terminationGracePeriodSeconds: 5
      initContainers:
      - name: log-shipper
        image: busybox:1.37
        restartPolicy: Always
        command: ["sh", "-c", "while true; do echo shipped batch; sleep 5; done"]
      containers:
      - name: report
        image: busybox:1.37
        command: ["sh", "-c", "echo report started; sleep 12; echo report done"]

report-classic is the same Job with log-shipper moved under containers. Forty seconds after starting both:

A regular-container sidecar holds the Job open
kubectl apply -f report-native.yaml -f report-classic.yaml
job.batch/report-native created
job.batch/report-classic created
sleep 40
kubectl get pods -l job-name
NAME                   READY   STATUS      RESTARTS   AGE
report-classic-g7hkq   1/2     NotReady    0          40s
report-native-dzshx    0/2     Completed   0          40s
kubectl wait --for=condition=complete job/report-native --timeout=5s
job.batch/report-native condition met
kubectl wait --for=condition=complete job/report-classic --timeout=5s
error: timed out waiting for the condition on jobs/report-classic
kubectl logs job/report-native -c report
report started
report done
kubectl get pod -l job-name=report-native -o jsonpath='{.items[0].status.initContainerStatuses[0].state.terminated.exitCode}'
137

report-classic finished its report and then sat at 1/2 NotReady, held open by a log shipper that will never exit. report-native completed. Its sidecar ended with exit code 137, and that does not count as a failure: the Job looks only at its regular containers. The pod’s restartPolicy of Never does not apply to the sidecar either, so a shipper that crashes partway through the report is restarted.

The 137 comes from how the kubelet stops a sidecar: SIGTERM, then SIGKILL when the pod’s terminationGracePeriodSeconds runs out. A shell loop running as PID 1 ignores SIGTERM, so it lives out the whole grace period, and the pod cannot complete until it is gone. With the default 30 seconds, every run of this Job would finish half a minute after its report; the template sets 5. A sidecar that exits on SIGTERM lets the pod complete as soon as the main container does.

Resource accounting

The scheduler places a pod by its effective requestThe request the scheduler uses for a whole pod: the larger of what initialization needs and what the running containers need, plus pod overhead., which is not a simple sum, because init containers run one at a time while sidecars keep running. Kubernetes works it out per resource, for two phases:

  • During initialization, for each init container, take its request plus the requests of every sidecar listed before it, because those are already running. The highest of these is the effective init request.
  • After initialization, add up the sidecars and the app containers, which all run together.

The pod’s effective request is the higher of the two, plus any pod overhead. The node keeps all of it reserved for the life of the pod, even after the init containers are gone. The same calculation applies to limits, to ResourceQuota, and to the pod-level cgroup.

apiVersion: v1
kind: Pod
metadata:
  name: orders
spec:
  initContainers:
  - name: proxy
    image: nginx:1.31
    restartPolicy: Always
    resources:
      requests:
        cpu: 100m
        memory: 64Mi
  - name: migrate
    image: busybox:1.37
    command: ["sh", "-c", "echo applying migrations; sleep 5; echo done"]
    resources:
      requests:
        cpu: 400m
        memory: 128Mi
  containers:
  - name: app
    image: ghcr.io/kx-labs/web:1.1
    resources:
      requests:
        cpu: 200m
        memory: 128Mi

For CPU, migrate runs while proxy is already up, so initialization needs 400m + 100m = 500m. Afterwards proxy and app need 100m + 200m = 300m. The effective request is 500m. For memory both phases come to 192Mi.

The node reserves the effective request
kubectl get pod orders -o wide
NAME     READY   STATUS    RESTARTS   AGE   IP           NODE         NOMINATED NODE   READINESS GATES
orders   2/2     Running   0          30s   10.244.2.2   kx-worker2   <none>           <none>
kubectl describe node kx-worker | grep -e 'Memory Requests' -e orders
  Namespace                   Name                               CPU Requests  CPU Limits  Memory Requests  Memory Limits  Age

Listing proxy after migrate would cut the CPU figure to 400m, because nothing would run alongside the migration. Order in initContainers changes what the pod costs.

Limits are enforced per container as usual. A sidecar that grows past its memory limit is OOM-killed and restarted with exit code 137 like any other container; in-place resize, GA in Kubernetes 1.35 on cgroup v2 nodes, changes requests and limits of a running pod without recreating it. The pod’s QoS class is computed across init, sidecar and app containers alike, so a sidecar without requests can keep the pod out of Guaranteed. QoS does not decide the order of node-pressure evictions: the kubelet ranks pods by whether their usage exceeds their requests, then by priority, then by usage relative to requests. QoS class sets each container’s oom_score_adj instead, 1000 for BestEffort, which steers the kernel’s OOM killer.

Migrating helper containers

Helpers written before native sidecars existed sit under containers and carry workarounds for problems sidecars solve. Migrating one takes four steps:

  1. Move the helper’s entry from containers to initContainers and add restartPolicy: Always.
  2. List it before anything that depends on it, including init containers that need it. Add a startupProbe if the app must not start until the helper accepts connections.
  3. Delete the shutdown workarounds. Common ones are a main container that touches a “done” file in a shared volume for the helper to notice, a call to a quitquitquit-style endpoint at the end of a Job’s script, and a long preStop sleep on a proxy so it outlives the app.
  4. Delete the startup workarounds, such as an app entrypoint that loops until the proxy port answers, or a postStart hook used to hold back the next container.

Then recheck the pod’s effective request, because the helper’s requests also count during initialization, for every init container listed after it.

restartPolicy set on a regular container, which the ContainerRestartRules feature allows (alpha in Kubernetes 1.34, beta and on by default since 1.35), controls how that container is restarted. It does not make it a sidecar: only an entry under initContainers with restartPolicy: Always starts first, stops last and stays out of a Job’s completion.

Run a Job with a native sidecar

  1. kubectl --context kind-kx apply -f https://k8s.io/examples/application/job/job-sidecar.yaml
  2. kubectl --context kind-kx wait --for=condition=complete job/myjob --timeout=120s
  3. kubectl --context kind-kx get pods -l job-name=myjob
  4. kubectl --context kind-kx logs job/myjob -c logshipper
  5. kubectl --context kind-kx get pod -l job-name=myjob -o jsonpath='{.items[0].status.initContainerStatuses[0].state.terminated.exitCode}'
  6. kubectl --context kind-kx delete job myjob

For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. The example from the Kubernetes docs writes one line to a shared volume and exits; the logshipper sidecar tails the file and is stopped once the main container has finished. The sidecar does not handle SIGTERM, so it is killed when the 30-second grace period runs out: the Job takes about half a minute and the exit code is 137.

Actual state

Check your understanding

5 checks

Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.

  1. Check 1 of 5

    A pod's only init container keeps failing, and the pod has the default restartPolicy. What does status.phase say?

  2. Check 2 of 5

  3. Check 3 of 5

    Which declaration makes a log shipper a native sidecar?

  4. Check 4 of 5

    A Job's pod has a native sidecar that ships logs forever and a main container that finishes after a minute. What happens when the main container exits 0?

  5. Check 5 of 5

    A pod has two native sidecars, proxy listed before log-shipper, and one app container. In what order are they stopped when the pod is deleted?

Lesson not yet reconciled

Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met

  • Sequence setup work with init containers and say what waits while they run. (not yet met)
  • Declare a native sidecar as an init container with restartPolicy Always. (not yet met)
  • Explain how native sidecars start before, and stop after, the main containers. (not yet met)
  • Explain why a Job with a native sidecar completes when its main container exits. (not yet met)

Pass every check above to reconcile this lesson.

Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.

Practice

Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.

Changed since the notes

This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.

Show 9 corrections
  1. Stale, true once, no longerPods Deep Dive

    The notes saidUnlike sidecar containers that run alongside the application, init containers complete and exit

    CorrectedNative sidecars are initContainers with restartPolicy: Always and keep running alongside the app. They have been stable since v1.33.

    Sourcekubernetes.io/docs/concepts/workloads/pods/sidecar-containers

  2. Nuance, true with conditionsPods Deep Dive

    The notes saidMemory limits are enforced strictly

    CorrectedMemory limits are still enforced by OOM kill. In-place Pod resize (GA in v1.35, needs cgroup v2) lets you change requests and limits without restarting the Pod.

    Sourcekubernetes.io/blog/2025/12/19/kubernetes-v1-35-in-place-pod-resize-ga

  3. Stale, true once, no longerPods Deep Dive

    The notes saidProbe mechanisms: HTTP, TCP, exec

    CorrectedgRPC probes are a fourth mechanism, GA since v1.27.

    Sourcekubernetes.dev/resources/keps/2727

  4. Stale, true once, no longerPods Deep Dive

    The notes saidPod conditions: PodScheduled, Initialized, ContainersReady, Ready

    CorrectedCurrent releases add PodReadyToStartContainers (stable since v1.37), DisruptionTarget, PodResizePending and PodResizeInProgress.

    Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle

  5. Wrong, not truePods Deep Dive

    The notes saidAlways is the default restartPolicy for pods created by controllers

    CorrectedAlways is the default restartPolicy for every Pod. Workload controllers such as Deployments accept only Always.

    Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle

  6. Wrong, not truePods Deep Dive

    The notes saidPods that fail might be restarted depending on restart policy

    CorrectedFailed is a terminal phase. Under Always or OnFailure the kubelet restarts the container in place with exponential backoff (CrashLoopBackOff), and the Pod stays Running.

    Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle

  7. Nuance, true with conditionsPods Deep Dive

    The notes saidPods stuck in ContainerCreating usually mean image pull issues

    CorrectedA failed pull shows as ErrImagePull or ImagePullBackOff; a slow pull of a large image does show ContainerCreating. A Pod stuck in ContainerCreating usually means the sandbox, networking (CNI/IP) or volume mounts failed, which are the prerequisites for PodReadyToStartContainers.

    Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle

  8. Nuance, true with conditionsPods Deep Dive

    The notes saidReadiness probes should check shared dependencies such as the database

    CorrectedKubernetes docs do suggest readiness checks for strict back-end dependencies. The risk, which those docs don't state, is that one shared-dependency failure marks every replica unready at once and empties the Service.

    Sourcekubernetes.io/docs/concepts/workloads/pods/probes

  9. Nuance, true with conditionsPods Deep Dive

    The notes saidBestEffort pods are the first to be evicted

    CorrectedThe kubelet doesn't use QoS class to order evictions. It ranks Pods by whether usage exceeds requests, then by priority, then by usage relative to requests. QoS class sets the OOM-killer adjustment (oom_score_adj 1000 for BestEffort).

    Sourcekubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction

Every correction across the guide, by note and topic.

Sources

Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .

  1. kubernetes.io/docs/concepts/workloads/pods/init-containers
  2. kubernetes.io/docs/concepts/workloads/pods/sidecar-containers
  3. kubernetes.io/docs/tutorials/configuration/pod-sidecar-containers
  4. kubernetes.io/docs/concepts/resource-management/effective-pod-requests-limits
  5. kubernetes.io/docs/concepts/workloads/pods/pod-termination
  6. kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
  7. kubernetes.io/docs/concepts/workloads/pods/probes
  8. kubernetes.io/docs/concepts/workloads/controllers/job
  9. kubernetes.io/docs/concepts/workloads/pods/pod-qos
  10. kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction
  11. kubernetes.io/docs/concepts/configuration/manage-resources-containers
  12. kubernetes.io/blog/2025/04/23/kubernetes-v1-33-release
  13. kubernetes.io/blog/2025/12/19/kubernetes-v1-35-in-place-pod-resize-ga
  14. kubernetes.dev/resources/keps/2727

Init containers and native sidecars

↓ ↑ step, 1 to 7 scene, Esc leave

kind cluster kxLast command: Nothing run yet