Kubernetes Init Containers: Setup Tasks Before Your App Starts

Kubernetes Init Containers: Setup Tasks Before Your App Starts

Almost every application needs something done before it can serve traffic. A configuration file has to be downloaded, a database schema migrated, a directory created with the right permissions, or a service the application depends on has to be reachable. On a virtual machine, those steps live in a startup script. In Kubernetes, they live in init containers, and understanding them is one of the fastest ways to make your Pods more reliable.

An init container runs inside a Pod before the application containers start. It shares the Pod network namespace and any volumes mounted into the Pod, it runs to completion, and then it stops. The application containers do not start until every init container has finished successfully. That ordering guarantee turns a fragile startup sequence into a declarative part of the Pod specification, visible in the same YAML file as the application, versioned in the same repository, and applied by the same deployment pipeline.

This guide explains how init containers work in current Kubernetes, when to use them, and when not to. You will see the four classic patterns that cover most real-world use cases, learn how resource requests are calculated when init containers are present, work through the most common failure states, and understand native sidecars, the newer form of init container that keeps running alongside your application. Every example is a runnable Pod manifest you can apply to a test cluster.

What Init Containers Are and Why They Exist

An init container is defined in the initContainers field of a Pod specification, alongside the regular containers field. It uses the same container definition as a regular container: an image, a command, arguments, environment variables, resource requests and limits, and volume mounts. The difference is not in what it is, but in when it runs and what happens after it finishes. A regular container is expected to keep running for the life of the Pod. An init container is expected to run a task and exit, and its exit code is the signal that the task succeeded or failed.

The most important property of init containers is that they separate setup from serving. An application container should start and be ready to handle requests immediately, with no knowledge of how its configuration was fetched or how its directories were prepared. When setup logic lives inside the application image or its entrypoint script, every application solves the same problems differently, and debugging a failed start means reading application logs mixed with setup logs. When setup lives in init containers, each step is a separate, named container with its own image, its own logs, and its own success or failure. You can look at a Pod and see exactly which setup step failed, because Kubernetes reports the init container by name and by status.

There are limits to what init containers can do, and knowing them early saves confusion later. A regular init container cannot have liveness, readiness, or startup probes, and it cannot have lifecycle hooks such as postStart or preStop. That makes sense: a probe checks whether a long-running process is healthy, and an init container is not a long-running process. It runs, it exits, and Kubernetes judges it by its exit code alone. If you need a container that runs setup and then keeps running, that is what native sidecars are for, and they are covered later in this guide.

Init containers share the Pod network namespace, so they see the same network interfaces and the same localhost as the application containers will see. They can reach the same Services, the same cluster DNS, and the same external endpoints, subject to the same NetworkPolicies. They also share any volumes mounted into the Pod, which is how they pass results to the application: an init container writes a file into a shared emptyDir volume, exits, and the application container later reads that file from the same volume. They do not share the application container filesystem. Each container still has its own writable layer, so a file written to a container-local path by an init container is invisible to the application. Shared volumes are the bridge between them.

How Init Containers Run: Sequential, Run to Completion, Then the App Starts

Init containers run one at a time, in the order they are listed in the Pod specification. The second init container does not start until the first has exited successfully, the third does not start until the second has exited successfully, and the application containers do not start until the last init container has exited successfully. There is no parallelism between init containers. If your setup steps genuinely do not depend on each other, you can still put them in separate init containers for clarity, but they will run in sequence and the total startup time is the sum of all of them.

Sequential execution is a feature, not a limitation, because it gives you a deterministic startup order. A common sequence is to wait for a dependency first, then fetch configuration, then fix permissions, then run a migration. Each step can assume the previous steps have completed. If any step fails, the sequence stops there, and the application never starts in a half-prepared state. That is the whole point: a Pod that starts its application is a Pod whose setup is known to be complete.

When an init container fails, the kubelet restarts the Pod according to the Pod restart policy, and the init containers run again from the beginning. With the default restart policy of Always, a failed init container is retried repeatedly, which is the correct behaviour for transient failures such as a dependency that is not ready yet. If the restart policy is Never, a failed init container causes the Pod to fail outright instead of being retried, which is useful for Jobs and other run-once workloads where retrying the whole Pod would be wrong.

The following Pod is the smallest useful example. It has one init container that writes a message into a shared emptyDir volume, and one application container that serves that message with a simple web server.

apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  containers:
    - name: app
      image: nginx:1.27
      ports:
        - containerPort: 80
      volumeMounts:
        - name: workdir
          mountPath: /usr/share/nginx/html
  initContainers:
    - name: write-message
      image: busybox:1.36
      command: ["sh", "-c", "echo 'Hello from the init container' > /workdir/index.html"]
      volumeMounts:
        - name: workdir
          mountPath: /workdir
  volumes:
    - name: workdir
      emptyDir: {}

Notice the structure. The init container and the application container mount the same volume, but at different paths, because each container has its own filesystem layout. The init container writes to /workdir/index.html, and the application container serves from /usr/share/nginx/html/index.html, which is the same file because both paths are backed by the same emptyDir volume. The emptyDir volume exists for the lifetime of the Pod and is deleted when the Pod is deleted, which is exactly the lifetime you want for setup artefacts that should not survive the Pod. If the setup output needs to survive Pod restarts, use a PersistentVolumeClaim instead, but be aware that a new Pod may then see stale output from a previous run.

kubectl apply -f init-demo.yaml
kubectl get pod init-demo
kubectl describe pod init-demo
kubectl logs init-demo -c write-message
kubectl exec init-demo -c app -- cat /usr/share/nginx/html/index.html

The Four Classic Init Container Patterns

Most init container usage falls into four patterns. Learning to recognise them helps you decide quickly whether an init container is the right tool, and it helps reviewers understand your Pod specification at a glance. The patterns are waiting for a dependency, fetching configuration, fixing permissions on a shared volume, and running a database migration. Many real Pods combine two or three of them in sequence, and that is fine, as long as each step is a separate init container with a clear name and a single responsibility.

The first pattern is waiting for a dependency. An application that starts before its database is ready will crash, restart, and crash again until the database appears, which fills logs with connection errors and can trigger alerts. An init container that waits for the dependency turns that crash loop into a calm wait. It repeatedly tries to connect, and only exits successfully when the dependency responds. The application then starts once, against a dependency that is known to be reachable. This does not replace readiness probes or retry logic inside the application, because a dependency can still go away after startup, but it removes the most common startup failure entirely.

A practical way to wait for a service is to use a small image with the right client tools and a loop with a timeout. The example below waits for a PostgreSQL service called db on port 5432, checking every two seconds and giving up after two minutes. The timeout matters: without it, a misconfigured service name would make the Pod wait forever, and the failure would be silent. With it, the init container fails, the Pod restarts, and the failure is visible in the Pod events. Choose the check to match the dependency. A TCP connection check proves the port is open, but a real query proves the database is actually accepting work. For a first version, a TCP check is usually enough.

apiVersion: v1
kind: Pod
metadata:
  name: wait-for-db
spec:
  containers:
    - name: app
      image: myapp:1.4.0
      ports:
        - containerPort: 8080
  initContainers:
    - name: wait-for-postgres
      image: postgres:16
      command: ["sh", "-c", "for i in $(seq 1 60); do pg_isready -h db -p 5432 && exit 0; echo waiting; sleep 2; done; exit 1"]

The second pattern is fetching configuration at startup. Some configuration is not known when the Pod is created, or it lives in a system that Kubernetes does not natively integrate with. An init container can call that system, download a configuration file, render a template, and write the result into a shared volume. The application then reads a plain file, with no knowledge of where it came from. This pattern is also useful when configuration needs transformation: an init container can take a generic template and a set of environment variables and produce the exact configuration the application expects, using tools that would bloat the application image if they were included there.

The third pattern is fixing permissions on a shared volume. Many applications run as a non-root user, but the PersistentVolume they mount is owned by root when it is first provisioned. The application then fails to write to its own data directory, and the failure looks like an application bug. An init container running as root can change the ownership or permissions of the volume before the application starts, and then exit. The application container runs as its normal user and finds a writable directory waiting for it. Note that setting fsGroup on the Pod makes Kubernetes change the group ownership of mounted volumes automatically, and in many cases that alone is enough. Use the init container when you need something fsGroup cannot do, such as creating a specific directory structure or setting different permissions on different subdirectories.

apiVersion: v1
kind: Pod
metadata:
  name: fix-permissions
spec:
  securityContext:
    fsGroup: 2000
  containers:
    - name: app
      image: myapp:1.4.0
      securityContext:
        runAsUser: 1000
        runAsGroup: 2000
      volumeMounts:
        - name: data
          mountPath: /data
  initContainers:
    - name: set-permissions
      image: busybox:1.36
      command: ["sh", "-c", "chown -R 1000:2000 /data && chmod 750 /data"]
      securityContext:
        runAsUser: 0
      volumeMounts:
        - name: data
          mountPath: /data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: app-data

The fourth pattern is running a database migration before the application starts. A new version of an application often needs a new database schema, and the application should not start serving traffic against the old schema. A migration init container runs the migration tool, applies the pending migrations, and exits successfully only when the schema is up to date. The application then starts against a schema it understands. This pattern works well for a single replica, but it needs care when several replicas start at the same time, because each replica would run its own migration init container. Most migration tools handle this with a lock in the database, so only one replica actually applies the migrations and the others wait or exit successfully when they find nothing to do. Check that your migration tool behaves this way before relying on the pattern with multiple replicas, and consider a Kubernetes Job for migrations in larger systems where a dedicated, separately controlled migration step is clearer. If the migration fails, the init container exits non-zero, the Pod restarts, and the migration is retried. A failed migration should never be ignored by deleting the Pod, because the next Pod will run the same migration and fail the same way.

These four patterns share a common design principle: each init container should do one thing, do it well, and report honestly. A single init container that waits for a database, downloads configuration, fixes permissions, and runs a migration is a shell script wearing a container costume, and it is just as hard to debug as the entrypoint script it replaced. Split the steps, name them clearly, and let Kubernetes show you which one failed.

Resource Requests and Limits: The Arithmetic That Surprises Everyone

Resource requests and limits behave differently for init containers than most people expect, and the difference has real scheduling consequences. For a Pod with only regular containers, the effective resource request is the sum of the requests of all the containers. For a Pod with init containers, the effective request is the larger of two numbers: the largest single init container request, or the sum of the application container requests. The same rule applies to limits, using the largest single init container limit or the sum of the application container limits, whichever is larger. The reasoning is that init containers run one at a time, so they never consume resources simultaneously, while application containers run together and their usage adds up.

Work through a concrete example. Suppose an application has two containers requesting 500 millicores of CPU each, for a sum of 1000 millicores. Suppose it also has an init container that requests 2000 millicores, because a migration tool is CPU hungry for a few seconds. The effective CPU request for the Pod is 2000 millicores, not 3000, because the init container and the application containers never run at the same time. The scheduler reserves 2000 millicores on a node for this Pod. Once the init container finishes and the application starts, the Pod is only using 1000 millicores, so 1000 millicores of the reservation sits unused for the life of the Pod. That is the cost of a heavy init container: it inflates the Pod scheduling request even though the usage is brief.

The practical lesson is to keep init container requests as small as you honestly can. A migration that needs a burst of CPU for ten seconds should still request what it needs to run well, because under-requesting CPU will throttle it and slow startup, but do not copy the application container requests into the init container out of habit. Measure what the init container actually uses, set its request close to that, and revisit the numbers when the setup task changes. The same applies to memory. An init container that exceeds its memory limit will be terminated with an out-of-memory error, just like any other container.

# Effective request = max(largest init request, sum of app requests)
# Example: app containers 500m + 500m = 1000m; init container 2000m
# Effective Pod CPU request = 2000m
kubectl describe pod web-7d9f6b4c5-x8k2p | grep -A 20 "Requests:"
kubectl top pod web-7d9f6b4c5-x8k2p --containers

Debugging Init Containers: Init:0/2, Init:Error and Init:CrashLoopBackOff

When a Pod is stuck in init, the Pod status tells you how far the sequence got. A status of Init:0/2 means zero of two init containers have completed. Init:1/2 means the first completed and the second is running or failing. Init:Error means an init container exited with a non-zero code. Init:CrashLoopBackOff means an init container has failed repeatedly and the kubelet is backing off before retrying it. Start every investigation with kubectl describe pod: its Init Containers section lists each init container by name, with its state, last termination details, and restart count, and the Events section shows the recent history.

kubectl get pods
kubectl describe pod web-7d9f6b4c5-x8k2p
kubectl logs web-7d9f6b4c5-x8k2p -c wait-for-postgres
kubectl logs web-7d9f6b4c5-x8k2p -c wait-for-postgres --previous

The logs are usually the fastest route to the cause. Use kubectl logs with the -c flag and the init container name. If the container has already restarted, add --previous to see the logs from the previous run, which is where the failure message lives. Work through the common causes in order: a typo in the image name or tag, which produces ImagePullBackOff; a wrong command, which exits immediately; a dependency that is not reachable, usually because the service name, port, or credentials are wrong; a volume mount that is missing, so the init container writes to its own filesystem and the application finds nothing; and a memory limit that is too small, which shows as OOMKilled. A Pod stuck at Init:0/1 with no error and no restart is not necessarily broken: it may be a wait loop with a long timeout, or a migration that takes minutes on a large database. Check what it has logged recently before concluding it is stuck, and give every wait loop and external call a timeout so a silent hang becomes a visible failure. For the application side of the same failure modes, see our Kubernetes CrashLoopBackOff fix guide.

Native Sidecars: Init Containers That Keep Running

For years, the sidecar pattern meant running a helper container alongside the application in the same Pod: a log shipper, a proxy, or a metrics exporter. The helper had to start before the application, but Kubernetes started all regular containers at the same time, with no ordering guarantee. Native sidecars solve this by letting an init container keep running, combining the ordering guarantee of an init container with the lifetime of a regular container. A native sidecar is an init container with restartPolicy: Always set on the container itself. The Pod starts it in sequence, waits for it to be ready, and then starts the application. When it exits, Kubernetes restarts it, and when the Pod is terminated, native sidecars are stopped before the application containers. This feature was alpha in Kubernetes 1.28, moved to beta and was enabled by default in 1.29, and became stable in 1.33.

apiVersion: v1
kind: Pod
metadata:
  name: native-sidecar
spec:
  containers:
    - name: app
      image: myapp:1.4.0
      ports:
        - containerPort: 8080
  initContainers:
    - name: proxy
      image: envoyproxy/envoy:v1.32
      restartPolicy: Always
      volumeMounts:
        - name: envoy-config
          mountPath: /etc/envoy
  volumes:
    - name: envoy-config
      configMap:
        name: envoy-config

The most common use case is a proxy the application needs before its first request: with a native sidecar, the application starts only after the proxy is up. Native sidecars also support what regular init containers do not: liveness, readiness, and startup probes, and lifecycle hooks. Use them where the ordering guarantee solves a real problem, such as a proxy, configuration watcher, or secrets agent that must be ready first. If the helper does not need to start before the application, a regular container is simpler. At runtime, a sidecar keeps consuming resources for the life of the Pod, unlike a run-once init container, so size it for steady-state usage and monitor its actual consumption.

Init Containers vs Sidecars vs Regular Containers

The choice comes down to two questions: does this container need to finish before the application starts, and does it need to keep running afterwards. If the answer to the first is yes and the second is no, use a regular init container: waiting, fetching, permission fixing, and migrating. If both answers are yes, use a native sidecar: proxies and configuration watchers that must be ready before the application and keep running. If the first answer is no and the second is yes, use a regular container: log shippers, metrics exporters, and background workers that do not need to be ready before the application starts.

Prefer small images for init containers, such as busybox for shell tasks, so Pods start faster. For foundations, see our Kubernetes tutorial for beginners and our Kubernetes Deployment YAML tutorial. The authoritative references are the init containers documentation and the Pod lifecycle documentation.

Frequently Asked Questions

Do init containers run before the application containers start?

Yes. Init containers run in the order listed, each one must exit successfully before the next starts, and the application containers start only after every init container has completed. If any init container fails, the application does not start.

Can an init container share files with the application container?

Yes, through a shared volume, usually an emptyDir volume. The init container writes files into it before exiting, and the application container reads them from the same volume. Containers do not share their own filesystems, so a file written to a container-local path is invisible to the application unless it goes through a shared volume.

Why is my Pod stuck in Init:0/1?

The Pod is waiting for its first init container to complete. Run kubectl describe pod to see its state and restart count, then kubectl logs with the init container name to see what it printed. Common causes are a wait loop for an unreachable dependency, a wrong image or command, a missing volume mount, or a long migration that is still working.

What is the difference between an init container and a native sidecar?

A regular init container runs once and exits before the application starts. A native sidecar is an init container with restartPolicy set to Always, so it starts in sequence before the application and then keeps running for the life of the Pod. Native sidecars support probes and lifecycle hooks, while regular init containers do not.

Do init containers affect Pod resource requests?

Yes. The effective Pod resource request is the larger of the largest single init container request or the sum of the application container requests, and the same rule applies to limits. A single heavy init container can inflate the Pod scheduling request even though it only runs for a few seconds.

Conclusion

Init containers turn application startup from an implicit script into an explicit, observable part of the Pod specification. They give you a deterministic order, a clear failure signal, and a clean separation between setup and serving. The four classic patterns cover most of what real applications need before they start, and native sidecars extend the same ordering guarantee to helpers that must keep running.

Start small: take one application that does setup in its entrypoint script, move a single step into an init container, and watch how the Pod behaves. Check the describe output, read the init container logs, and confirm the shared volume handoff works. That discipline becomes a habit, and your Pods will start reliably, fail clearly, and be easier for the next person to understand.

Scroll to Top