Overview and What You Will Learn
A Kubernetes pod is a group of containers that share one network identity and can share volumes. Two patterns decide how those containers are used. An init container runs to completion, one at a time, before the application starts, and is used for setup and dependency checks. A sidecar runs alongside the application for the pod's whole life, and is used for logging, proxying and secrets refresh. In this lab, you will watch a pod wait on a dependency, pass configuration through a shared volume, ship logs with a sidecar, and use a native sidecar that lets a Job finish cleanly.
- Explaining what containers in a pod share
- Using init containers to wait for dependencies and prepare configuration
- Sharing files between containers with an
emptyDirvolume - Running a logging sidecar next to an application
- Using native sidecars with
restartPolicy: Alwaysin Kubernetes 1.29 and later - Calculating a pod's effective resource request
- Debugging a pod stuck in an init state
Why This Matters in Production
At a company like Cloudflare, services start in an order that cannot be guaranteed: the app may come up before its database, and logs have to leave the pod before it disappears. Without init containers the application starts, fails to connect, and falls into CrashLoopBackOff. Without sidecars every team builds log shipping and proxy logic into every application. Using the two patterns correctly removes whole classes of startup bugs and observability gaps.
Core Principles
All containers in a pod share the same IP address, so they reach each other on localhost, and they can share files through volumes that each container mounts. They do not need to know about each other. They cooperate through localhost and shared paths.
port 8080] SC[log-forwarder
sidecar] VOL[(emptyDir volume
/var/log/app)] end APP -->|writes logs| VOL VOL -->|reads logs| SC SC --> LOKI([Central log store]) classDef app fill:#326CE5,color:#FFFFFF classDef side fill:#8B5CF6,color:#FFFFFF classDef store fill:#475569,color:#FFFFFF classDef ext fill:#10B981,color:#FFFFFF class APP app class SC side class VOL store class LOKI ext
Init containers run in order, each to completion, before any regular container starts. If one fails, the kubelet retries it when the pod's restartPolicy is Always or OnFailure, and with Never the pod fails. The application container never starts until every init container has succeeded.
runs, succeeds] --> I2[init-fetch-config
runs, succeeds] I2 --> M([payments-api
and sidecars start]) classDef init fill:#F97316,color:#FFFFFF classDef main fill:#10B981,color:#FFFFFF class I1,I2 init class M main
Init containers rerun whenever the pod is recreated or its sandbox restarts, so they must be safe to run more than once. They do not support readiness probes, and they cannot be used to hold the pod for a dependency forever without a timeout.
Regular containers in a pod start with no guaranteed order. Before Kubernetes 1.29, a sidecar declared as a regular container could start after the application, and in a Job it kept the pod alive after the main task finished, so the Job never completed. Native sidecars solve both problems. You declare a sidecar as an init container with restartPolicy: Always. Kubernetes starts it before the main containers, waits for it to be ready, keeps it running for the pod's life, and on shutdown stops it after the main containers. The feature is beta and on by default from Kubernetes 1.29, and it is stable from 1.33.
A pod's effective resource request combines its containers in a specific way:
| Containers | How requests combine | Example CPU |
|---|---|---|
| Init containers | The largest single init container | max(50m, 200m) = 200m |
| Regular containers | The sum of all of them | 500m + 100m = 600m |
| The pod | The larger of the two results | 600m |
Native sidecars are restartable init containers, and their requests are added to the sum of the regular containers because they keep running.
Detailed Step-by-Step Practical Lab
This lab needs a Kubernetes cluster and kubectl. Step 5 needs Kubernetes 1.29 or later.
- Create a namespace and a pod whose init container waits for a database Service that does not exist yet. The init container checks DNS first, then the TCP port:
kubectl create namespace pods-labkubectl config set-context --current --namespace=pods-lab cat << 'EOF' | kubectl apply -f -apiVersion: v1kind: Podmetadata: name: payments-api labels: app: payments-apispec: initContainers: - name: init-wait-for-db image: busybox:1.36 command: - sh - -c - | until nslookup db-service.pods-lab.svc.cluster.local; do echo "DNS not ready for db-service, retrying in 3s"; sleep 3 done until nc -z db-service 5432; do echo "db-service:5432 not reachable, retrying in 3s"; sleep 3 done echo "db-service is ready" containers: - name: payments-api image: nginx:1.27-alpine ports: - containerPort: 80EOF kubectl get pod payments-apikubectl logs payments-api -c init-wait-for-db --tail=3The pod is stuck in Init:0/1, and the init container log shows it retrying. The application container has not started.
- Create the missing dependency, and watch the pod move on by itself:
kubectl create deployment db --image=nginx:1.27-alpinekubectl expose deployment db --name=db-service --port=5432 --target-port=80 kubectl get pod payments-api -wThe status goes from Init:0/1 to PodInitializing to Running once the Service answers. Stop the watch with Ctrl+C. An init check does not replace connection retries in your application, because the dependency can still fail later.
- Pass configuration from an init container to the application through a shared
emptyDirvolume. The init container writes a file, and the application mounts it read-only:
cat << 'EOF' | kubectl apply -f -apiVersion: v1kind: Podmetadata: name: config-demospec: volumes: - name: app-config emptyDir: {} initContainers: - name: init-fetch-config image: busybox:1.36 command: - sh - -c - | echo "environment=production" > /config/app.conf echo "region=ap-south-1" >> /config/app.conf echo "config written" volumeMounts: - name: app-config mountPath: /config containers: - name: app image: busybox:1.36 command: ["sh", "-c", "cat /etc/app/app.conf; sleep 3600"] volumeMounts: - name: app-config mountPath: /etc/app readOnly: trueEOF kubectl wait --for=condition=ready pod/config-demo --timeout=60skubectl logs config-demo -c appThe application prints the two lines written by the init container. In production the init step might fetch a rendered config from a secrets manager using the pod's identity, not a static token.
- Add a logging sidecar. The application writes to a log file, and the sidecar streams that file so a log agent can pick it up. Both containers mount the same volume:
cat << 'EOF' | kubectl apply -f -apiVersion: v1kind: Podmetadata: name: logging-demospec: volumes: - name: app-logs emptyDir: {} containers: - name: payments-api image: busybox:1.36 command: - sh - -c - | i=0 while true; do echo "$(date +%T) handled request $i" >> /var/log/app/app.log i=$((i + 1)); sleep 2 done volumeMounts: - name: app-logs mountPath: /var/log/app - name: log-forwarder image: busybox:1.36 command: ["sh", "-c", "touch /var/log/app/app.log; tail -n +1 -F /var/log/app/app.log"] volumeMounts: - name: app-logs mountPath: /var/log/app resources: requests: cpu: 50m memory: 32Mi limits: memory: 64MiEOF kubectl wait --for=condition=ready pod/logging-demo --timeout=60ssleep 10kubectl logs logging-demo -c log-forwarder --tail=5kubectl get pod logging-demoThe pod reports 2/2 ready containers, and the sidecar's log shows the application's output. The sidecar has real resource requests and a memory limit, which matters in production.
- Use a native sidecar in a Job. The sidecar is an init container with
restartPolicy: Always. When the main container finishes, Kubernetes stops the sidecar, so the Job completes. As a regular container, the same sidecar would keep the pod running and the Job would never finish:
cat << 'EOF' | kubectl apply -f -apiVersion: batch/v1kind: Jobmetadata: name: batch-with-sidecarspec: backoffLimit: 0 template: spec: restartPolicy: Never volumes: - name: work emptyDir: {} initContainers: - name: log-tail image: busybox:1.36 restartPolicy: Always command: ["sh", "-c", "touch /work/out.log; tail -n +1 -F /work/out.log"] volumeMounts: - name: work mountPath: /work containers: - name: batch-task image: busybox:1.36 command: - sh - -c - | for i in 1 2 3; do echo "step $i done" >> /work/out.log; sleep 2; done volumeMounts: - name: work mountPath: /workEOF kubectl wait --for=condition=complete --timeout=90s job/batch-with-sidecarkubectl logs job/batch-with-sidecar -c log-tailThe Job completes and the sidecar log contains the three steps. If your cluster is older than 1.29, the restartPolicy field is rejected on an init container, so use a regular sidecar and add shutdown handling instead.
- Debug a stuck init container. These commands cover the common cases:
kubectl get pod payments-api -o jsonpath='{.status.initContainerStatuses[*].state}{"\n"}'kubectl logs payments-api -c init-wait-for-dbkubectl logs payments-api -c init-wait-for-db --previouskubectl describe pod payments-api | grep -A6 EventsLook for Back-off restarting failed init container in the events. If the init container logs bad address for a hostname, the problem is DNS, not the dependency.
- Clean up:
kubectl config set-context --current --namespace=defaultkubectl delete namespace pods-labProduction Best Practices & Common Pitfalls
Common MistakeChecking a dependency by hostname in an init container without confirming that DNS works. The init container then fails with a confusing error. Run
nslookupfirst, as in step 1, so a DNS failure is obvious and separate from a connection failure.
TipGive sidecars real resource requests and limits. A log forwarder with no requests gets squeezed or killed under load, and it then stops shipping logs exactly when you need them during an incident.
RememberA mounted Secret volume updates inside a running pod after a short delay, but environment variables and
subPathmounts never do. Read rotated secrets from files, or use a sidecar or controller that refreshes them, instead of relying on environment variables.
- Do not run database migrations in an init container for a multi-replica Deployment. Every replica runs the migration at once and the copies race. Use one Job or a pre-deploy hook, and make the init container wait for it instead.
- Make init containers idempotent. They rerun whenever the pod is recreated, so a second run must not break anything.
- Prefer native sidecars on Kubernetes 1.29 and later. They give a defined startup and shutdown order, and they let Jobs complete.
- Know the service mesh model. Istio injects an
istio-proxysidecar that intercepts inbound and outbound traffic and enforces mTLS, though its ambient mode removes the per-pod sidecar. - Store secrets in memory when sharing them. An
emptyDirwithmedium: Memorykeeps them off disk, but the memory counts against the container's limit. - Use sidecars sparingly. Each one adds requests and limits to every replica, so a pattern that one node agent could serve is often cheaper as a DaemonSet.
- Share a process namespace only when needed.
shareProcessNamespace: truelets a sidecar see the application's processes, which helps debugging but widens the blast radius.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl logs POD -c INIT_NAME |
Read an init container's logs |
kubectl logs POD -c INIT_NAME --previous |
Read the last failed attempt |
kubectl get pod POD -w |
Watch init progress such as Init:1/2 |
kubectl describe pod POD |
Show events for init failures |
kubectl logs POD -c SIDECAR_NAME |
Read a sidecar's logs |
kubectl get pod POD -o jsonpath='{.status.initContainerStatuses[*].state}' |
Show the state of every init container |
| Problem | Cause | Fix |
|---|---|---|
Pod stuck in Init:0/N |
The first init container cannot finish | Read its logs and check the dependency |
Init:CrashLoopBackOff |
An init command exits non-zero | Use --previous logs and fix the command |
| Job never completes | A regular sidecar keeps the pod alive | Use a native sidecar or stop it from the main container |
restartPolicy rejected on an init container |
Cluster is older than 1.29 | Upgrade, or use a regular sidecar |
| Sidecar OOMKilled | No memory request or limit | Set realistic requests and limits |
| Config file missing in the app | Volume not mounted in both containers | Mount the same volume in the init and app containers |