Skip to main content

Using Init Containers and Sidecars in Pods

Use init containers for startup setup and sidecars for logging, proxies and secrets refresh, including native sidecars in Kubernetes 1.29 and later.

52 Terms

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 emptyDir volume
  • Running a logging sidecar next to an application
  • Using native sidecars with restartPolicy: Always in 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.

flowchart TD subgraph POD[Pod payments-api] APP[payments-api
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.

flowchart LR I1[init-wait-for-db
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.

  1. 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:
Bash
kubectl create namespace pods-lab
kubectl config set-context --current --namespace=pods-lab
cat << 'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: payments-api
labels:
app: payments-api
spec:
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: 80
EOF
kubectl get pod payments-api
kubectl logs payments-api -c init-wait-for-db --tail=3

The pod is stuck in Init:0/1, and the init container log shows it retrying. The application container has not started.

  1. Create the missing dependency, and watch the pod move on by itself:
Bash
kubectl create deployment db --image=nginx:1.27-alpine
kubectl expose deployment db --name=db-service --port=5432 --target-port=80
kubectl get pod payments-api -w

The 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.

  1. Pass configuration from an init container to the application through a shared emptyDir volume. The init container writes a file, and the application mounts it read-only:
Bash
cat << 'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: config-demo
spec:
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: true
EOF
kubectl wait --for=condition=ready pod/config-demo --timeout=60s
kubectl logs config-demo -c app

The 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.

  1. 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:
Bash
cat << 'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: logging-demo
spec:
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: 64Mi
EOF
kubectl wait --for=condition=ready pod/logging-demo --timeout=60s
sleep 10
kubectl logs logging-demo -c log-forwarder --tail=5
kubectl get pod logging-demo

The 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.

  1. 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:
Bash
cat << 'EOF' | kubectl apply -f -
apiVersion: batch/v1
kind: Job
metadata:
name: batch-with-sidecar
spec:
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: /work
EOF
kubectl wait --for=condition=complete --timeout=90s job/batch-with-sidecar
kubectl logs job/batch-with-sidecar -c log-tail

The 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.

  1. Debug a stuck init container. These commands cover the common cases:
Bash
kubectl get pod payments-api -o jsonpath='{.status.initContainerStatuses[*].state}{"\n"}'
kubectl logs payments-api -c init-wait-for-db
kubectl logs payments-api -c init-wait-for-db --previous
kubectl describe pod payments-api | grep -A6 Events

Look 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.

  1. Clean up:
Bash
kubectl config set-context --current --namespace=default
kubectl delete namespace pods-lab

Production Best Practices & Common Pitfalls

Common Mistake

Checking a dependency by hostname in an init container without confirming that DNS works. The init container then fails with a confusing error. Run nslookup first, as in step 1, so a DNS failure is obvious and separate from a connection failure.

Tip

Give 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.

Remember

A mounted Secret volume updates inside a running pod after a short delay, but environment variables and subPath mounts 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-proxy sidecar 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 emptyDir with medium: Memory keeps 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: true lets 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

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Workload Management

All 6 Topics

Frequently Asked Questions

Is Using Init Containers and Sidecars in Pods free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Using Init Containers and Sidecars in Pods topic cover?

Use init containers for startup setup and sidecars for logging, proxies and secrets refresh, including native sidecars in Kubernetes 1.29 and later.

Found a mistake, an outdated step or a broken link?