Sidecars and lifecycle
When a helper needs to keep running
A sidecar is a companion process that adds a local capability to an application. Containers in one Pod share its network identity and may exchange files through mounted volumes; they are scheduled together and share a Pod lifecycle. An ordinary companion listed under containers runs as a regular application container. It does not get the special start/stop ordering of a native sidecar. A native sidecar is declared under initContainers with its own restartPolicy: Always. Native sidecars became stable in Kubernetes v1.33; the feature was enabled by default starting in v1.29. Check older cluster support and feature configuration before using this syntax.
Read the native sidecar manifest
The formatter starts before the finite prepare step. It waits for the synthetic inventory file and prints one formatted line; reader reads that same file. The formatter runs beyond reader startup and can be stopped during Pod termination. This is a demonstration of local data exchange, not a reliable log pipeline: output ordering and whether the formatter prints before shutdown are not guaranteed. The bounded scripts and Pod deadline avoid unbounded work. No host files, API credentials or public network are used. The placeholder image is intentionally non-deployable.
apiVersion: v1kind: Podmetadata: name: catalog-sidecar namespace: pattern-studyspec: restartPolicy: Never activeDeadlineSeconds: 120 terminationGracePeriodSeconds: 15 automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 runAsGroup: 10001 fsGroup: 10001 seccompProfile: type: RuntimeDefault volumes: - name: work emptyDir: sizeLimit: 8Mi initContainers: - name: formatter image: example.invalid/bytemind/python:offline command: - python3 - -c args: - "from pathlib import Path\nimport time\nfor _ in range(60):\n p = Path('/work/catalog.txt')\n\ \ if p.exists():\n print('CATALOG: ' + p.read_text(encoding='utf-8').strip(),\ \ flush=True)\n break\n time.sleep(1)\ntime.sleep(90)" securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL resources: requests: cpu: 50m memory: 32Mi limits: cpu: 100m memory: 64Mi volumeMounts: - name: work mountPath: /work readOnly: false restartPolicy: Always - name: prepare image: example.invalid/bytemind/python:offline command: - python3 - -c args: - 'from pathlib import Path
Path(''/work/catalog.txt'').write_text(''books=3\n'', encoding=''utf-8'')' securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL resources: requests: cpu: 200m memory: 64Mi limits: cpu: 400m memory: 128Mi volumeMounts: - name: work mountPath: /work readOnly: false containers: - name: reader image: example.invalid/bytemind/python:offline command: - python3 - -c args: - 'from pathlib import Path
print(Path(''/work/catalog.txt'').read_text(encoding=''utf-8'').strip())
import time
time.sleep(3)' securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL resources: requests: cpu: 100m memory: 32Mi limits: cpu: 200m memory: 64Mi volumeMounts: - name: work mountPath: /work readOnly: trueStartup and readiness are different
A native sidecar can unblock the next init step after its process is considered started (or after its startup probe succeeds, if configured). A readiness probe, if configured, contributes to Pod readiness but does not itself serve as the startup gate. A liveness probe can trigger a restart. In the example there is no startup probe, so reader must not assume formatter has initialized any application-level dependency. The file is instead produced by the finite prepare step. If a helper must expose a working local endpoint before the next init begins, use a startup probe suited to that endpoint. A readiness probe should check the capability needed to serve traffic, not merely file existence.
Shutdown and finite Jobs
On graceful Pod termination, native sidecars are stopped after the regular application containers, in reverse order of native sidecar declaration. The Pod grace budget is shared, so this is not a guarantee of time to flush every record; a slow app can consume the budget. A native sidecar does not hold a Job open after the main task finishes. An ordinary long-running companion under containers can prevent completion. An ordinary init container is already finished before application startup. Choose based on lifecycle, not just container count.
Account for overlapping requests
For each resource, walk initContainers in order. A running native sidecar contributes to all later initialization steps and steady operation. The formatter requests 50m CPU and 32Mi memory. During prepare the combined request is 250m and 96Mi; steady operation requests 150m and 64Mi. Therefore this example needs 250m CPU and 96Mi memory for scheduling, excluding overhead and Pod-level overrides. Reversing the init list would reduce the CPU maximum to 200m and memory maximum to 64Mi, but would also change startup order. The peak is calculated separately for each resource. See the resource accounting fixture for different orderings.
Choose a companion or separate workload
An adapter can translate a local output format; an ambassador can act as a local proxy; a log helper can process synthetic application logs. These are patterns, not required components. A companion is useful when it needs local shared state or lifecycle coordination. A separate Deployment is usually more appropriate when the helper must scale, deploy or recover independently or serves many Pods. A shared Pod is not a strong security separation for mutually untrusted workloads. Do not mount host logs or forward private data in this lab.
Practice and inspection
Use sidecar-cases.json and resource-cases.json to trace startup, shutdown and compute requests. Inspect the expected initContainerStatuses rather than assuming every long-running process is listed in containerStatuses. The following read-only example would require the approved isolated lab context; no kubectl command was executed. Further reading: https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/; https://kubernetes.io/docs/concepts/workloads/pods/pod-termination/; https://kubernetes.io/docs/concepts/resource-management/effective-pod-requests-limits/.
kubectl --context bytemind-lab -n pattern-study get pod catalog-sidecar -o jsonkubectl --context bytemind-lab -n pattern-study logs catalog-sidecar -c formatterCheck Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sidecars and lifecycle — knowledge check
Apply the chapter concepts using synthetic offline scenarios.
Which declaration selects native sidecar behavior on a supporting cluster?
A native sidecar has a startup probe that has not succeeded. Can the next init step begin normally?
Native sidecars A then B are listed before the app. In graceful shutdown, what order is intended?
A native sidecar requests 70m, later ordinary init requests 240m, app requests 120m. What effective CPU request is needed without overhead?
A helper serves many unrelated Pods and scales independently. Which is a reasonable starting design?