Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

Init containers and sidecars: prepare and support your Pods

By updated

Improve this page

Logo Kubernetes

An application that starts before its database crashes, and an application that writes its logs to a file shows nothing of them to kubectl logs. Init containers solve the first problem: they run before the application, one at a time, and each one must succeed for the next step to start. Sidecars solve the second: they run next to the application and do a side job, such as relaying a log file. In this lesson, you make a Pod wait with an init container until its dependency exists, then you add a native sidecar that relays its lines.

You need the lesson Pods, the demo cluster from First cluster and the Service covered in Services. The db Service of the demonstration is provided without explanation: just remember that it gives a stable name to Pods.

What you will learn

  • Declare an init container and read the Init:1/2 progress of a Pod
  • Make an application wait with a bounded wait loop
  • Share a file between an init container and the application with an emptyDir volume
  • Add a native sidecar (an init container with restartPolicy: Always) and read its logs with -c
  • Tell the sidecar pattern from the native sidecar, and choose between an init container and a sidecar
  • Read Defaulted container when kubectl logs picks the container by itself

What the containers of a Pod share

The containers of a Pod share several resources, which is why one can prepare what the other uses.

ResourceWhat is shared
NetworkSame IP address, localhost works between containers
VolumesThose declared in the Pod, provided each container mounts them
NodeAll the containers run on the same node
LifetimeThey are born and disappear with the Pod; their startups and shutdowns, however, are ordered

The filesystem, on the other hand, is not shared: each container sees the one from its image. To exchange files, the Pod declares a volume that both containers mount.

Understanding init containers

An init container is a container that runs before the main containers of the Pod and that must finish successfully. It is declared in spec.initContainers, a list separate from spec.containers. This separation gives Kubernetes the order: everything in initContainers runs and finishes before the first application container starts.

How init containers behave

Four rules sum up how they work.

  • They run one at a time, in declaration order.
  • Each one must finish with exit code 0 before the next one starts.
  • On failure, the kubelet restarts it according to the Pod's restartPolicy.
  • The application containers start only once all the init containers have succeeded.

An ordinary init container accepts neither probes (livenessProbe, readinessProbe, startupProbe) nor lifecycle: it must run to the end, not run forever. This restriction only targets init containers that have an end; the one that carries restartPolicy: Always is a native sidecar and accepts them. The server refuses a probe on an ordinary init container with this message:

The Pod "init-sonde" is invalid: spec.initContainers[0].readinessProbe: Forbidden: may not be set for init containers without restartPolicy=Always

The same refusal applies to livenessProbe, startupProbe and lifecycle.

Init container use cases

What these uses have in common is a preliminary task, with an end, that the application needs in order to start.

Use caseConcrete example
Fetch filesDownload a configuration from a repository
Wait for a serviceCheck that a database answers before launching the application
Initialize dataApply migrations
Prepare the filesystemCreate directories, unpack an archive

Adjusting permissions on a volume often comes up in this list. Before writing an init container for chmod or chown, check whether securityContext (runAsUser, runAsGroup, fsGroup) already meets the need, as shown in Application volumes.

Creating an init container

The demonstration follows a single thread. A Pod app needs a dependency, the Service db, which does not exist yet. A first init container prepares a configuration file, a second waits for db, then the application starts. You then create db and watch the Pod move to Running on its own. Finally, you add a sidecar that relays the application's log file.

The demo cluster is assumed to exist. You work in a dedicated namespace, deleted at the end:

Terminal window
kubectl config use-context kind-demo && kubectl create namespace sidecars

Captured output:

Switched to context "kind-demo".
namespace/sidecars created

The kind-demo context is active and the namespace exists. The following commands carry -n sidecars.

Sharing a folder between containers: the emptyDir volume

The simplest volume for exchanging files inside a Pod is emptyDir: an empty folder, created when the Pod starts on a node. It survives a container restart and disappears with the Pod. The init container preparer writes a file into it, and the application and the sidecar will read it. The other volume types, and what emptyDir accepts as options, are covered in Application volumes.

The Pod manifest

The file declares three things. preparer writes mode=demo into /partage/config.txt then finishes. attendre-db queries http://db every two seconds, at most 60 times, and exits with an error if db never answers. The application reads the configuration file then appends a line every three seconds to /partage/app.log, without writing anything to its standard output.

The names and the echo messages of this lesson are in French on purpose, so that the outputs stay those of the tested cluster: preparer means "prepare", attendre-db "wait for db", partage "share", "essai" an "attempt", "db ne répond pas encore" "db is not answering yet", "db répond après N essai(s)" "db answers after N attempt(s)", "db n'a pas répondu à temps" "db did not answer in time", "config lue" "config read" and "requête traitée" "request handled".

Terminal window
mkdir -p ~/atelier-k8s/sidecars && cd ~/atelier-k8s/sidecars
cat > app.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: app
labels:
app: app
spec:
initContainers:
- name: preparer
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command: ["sh", "-c", "echo mode=demo > /partage/config.txt"]
volumeMounts:
- name: partage
mountPath: /partage
- name: attendre-db
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command:
- sh
- -c
- |
for i in $(seq 1 60); do
if wget -q -T 2 -O /dev/null http://db; then
echo "db répond après $i essai(s)"
exit 0
fi
echo "essai $i : db ne répond pas encore"
sleep 2
done
echo "db n'a pas répondu à temps"
exit 1
containers:
- name: app
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command:
- sh
- -c
- |
echo "config lue : $(cat /partage/config.txt)"
while true; do
echo "$(date +%T) requête traitée" >> /partage/app.log
sleep 3
done
volumeMounts:
- name: partage
mountPath: /partage
volumes:
- name: partage
emptyDir: {}
EOF

The loop is bounded to 60 attempts: an unbounded wait would hide the failure of a dependency that will never arrive, whereas here the Pod ends up failing and says so in the logs of attendre-db.

Watching the startup

Apply the Pod, wait eight seconds and read its state:

Terminal window
kubectl apply -f app.yaml -n sidecars && sleep 8 && kubectl get pod app -n sidecars
pod/app created
NAME READY STATUS RESTARTS AGE
app 0/1 Init:1/2 0 8s

Init:1/2 means that one init container out of two has finished: preparer is done, attendre-db is still running. READY 0/1 is normal, the application has not started. To find out what attendre-db is doing, kubectl logs accepts -c followed by the name of a container, init containers included:

Terminal window
kubectl logs app -n sidecars -c attendre-db
wget: bad address 'db'
essai 1 : db ne répond pas encore

On a node that has never pulled the busybox image, the first pull takes time and the command may print nothing eight seconds after the apply. Wait a few seconds and run it again: the log appears as soon as attendre-db has written its first line.

The wget: bad address 'db' line is the error from wget: the name db does not resolve, since the Service does not exist. The essai 1 line comes from the script. The same option on preparer shows nothing:

Terminal window
kubectl logs app -n sidecars -c preparer
(no output)

preparer prints nothing because it wrote to the volume, not to its output. An empty log therefore does not tell you whether the container did its work: it is the state of the Pod (Init:1/2) that shows it finished.

Init container: waiting for a service

Now create the dependency. The db.yaml file declares an nginx Deployment and a Service named db, provided without explanation here (see Services).

Terminal window
cat > db.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: db
spec:
replicas: 1
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: nginx
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: db
spec:
selector:
app: db
ports:
- port: 80
targetPort: 80
EOF
kubectl apply -f db.yaml -n sidecars && kubectl wait --for=condition=Ready pod/app -n sidecars --timeout=180s
deployment.apps/db created
service/db created
pod/app condition met

You did nothing else: attendre-db kept querying db and finished as soon as the Service answered, which unblocked the application. Check the state and the end of the wait log:

Terminal window
kubectl get pod app -n sidecars && kubectl logs app -n sidecars -c attendre-db | tail -n 3
NAME READY STATUS RESTARTS AGE
app 1/1 Running 0 17s
wget: can't connect to remote host (10.96.99.192): Connection refused
essai 2 : db ne répond pas encore
db répond après 3 essai(s)

The Pod is Running with 0 restarts: the wait did not cause a failure. The Connection refused message comes from wget, which found the Service before the nginx Pod was ready; the third attempt succeeded. The number of attempts, the Service address and the age of the Pod vary from one run to the next.

A Service that exists does not prove that the dependency is ready: test what the application really needs. Now check that the application read the prepared file:

Terminal window
kubectl exec app -n sidecars -c app -- cat /partage/config.txt
mode=demo

The file written by preparer is readable by app: the emptyDir volume does link the two containers.

Two ways of talking about sidecars

The word designates two things. The sidecar pattern is simply a second container in spec.containers, which starts at the same time as the application, with no guaranteed order. The native sidecar is an init container with restartPolicy: Always: Kubernetes starts it before the application, lets it run and stops it after the application. This is the form this lesson uses: the guaranteed order at startup and shutdown sets it apart from the pattern.

Native sidecar (Kubernetes feature)

The native sidecar goes in initContainers, after the init containers that must precede it. Because it carries restartPolicy: Always, it does not block what follows: Kubernetes considers its startup successful and moves on to the next item. It also accepts probes and hooks, unlike an ordinary init container. On Kubernetes 1.37, there is nothing to enable.

On the diagram below, look at the order of the bars. The ordinary init containers finish, the sidecar starts then stays active, and the application starts afterwards. At shutdown, the order reverses: the sidecar is stopped last.

Timeline of a Pod: two init containers run then terminate, the native sidecar starts and stays active, then the main container starts. When the Pod is deleted, the main container stops first and the native sidecar last.Pod deleted① Init container 1runs, then exits② Init container 2runs, then exits③ Native sidecarstarts and keeps running④ Main containerstarts⑤ Main containerstops⑥ Native sidecarstops last
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

Differences between the two approaches

The table compares the two forms on what sets them apart: where they are declared and the startup and shutdown order.

CriterionSidecar patternNative sidecar
Declared incontainersinitContainers, with restartPolicy: Always
StartupAt the same time as the application, no orderBefore the application
ShutdownNo guaranteed orderAfter the application

For the rest, the two behave the same: they accept probes and hooks, count in READY and are read with kubectl logs -c <name>.

Creating a native sidecar

You cannot add an init container to a Pod that already exists. The app-sidecar.yaml file takes app.yaml and adds journal as a third init container, with restartPolicy: Always and the volume mounted read-only. It runs tail -F /partage/app.log, which follows the file even if it does not exist yet. The name journal means "log".

Terminal window
cat > app-sidecar.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: app
labels:
app: app
spec:
initContainers:
- name: preparer
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command: ["sh", "-c", "echo mode=demo > /partage/config.txt"]
volumeMounts:
- name: partage
mountPath: /partage
- name: attendre-db
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command:
- sh
- -c
- |
for i in $(seq 1 60); do
if wget -q -T 2 -O /dev/null http://db; then
echo "db répond après $i essai(s)"
exit 0
fi
echo "essai $i : db ne répond pas encore"
sleep 2
done
echo "db n'a pas répondu à temps"
exit 1
- name: journal
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
restartPolicy: Always
command: ["sh", "-c", "tail -F /partage/app.log"]
volumeMounts:
- name: partage
mountPath: /partage
readOnly: true
containers:
- name: app
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command:
- sh
- -c
- |
echo "config lue : $(cat /partage/config.txt)"
while true; do
echo "$(date +%T) requête traitée" >> /partage/app.log
sleep 3
done
volumeMounts:
- name: partage
mountPath: /partage
volumes:
- name: partage
emptyDir: {}
EOF
kubectl apply -f app-sidecar.yaml -n sidecars
The Pod "app" is invalid: spec.initContainers: Forbidden: pod updates may not add or remove containers

The server refuses: an existing Pod neither gains nor loses a container, init or not. "Adding a sidecar" therefore means writing the new version of the manifest and recreating the Pod. The deletion waits for the 30-second grace period: the sh of app does not react to the stop signal, and Kubernetes ends up killing it:

Terminal window
kubectl delete pod app -n sidecars --wait=true && kubectl apply -f app-sidecar.yaml -n sidecars && kubectl wait --for=condition=Ready pod/app -n sidecars --timeout=120s
pod "app" deleted from sidecars namespace
pod/app created
pod/app condition met

The block took 34 seconds, almost all of it in the deletion. The Pod starts quickly, and attendre-db succeeds right away since db already answers:

Terminal window
kubectl get pod app -n sidecars
NAME READY STATUS RESTARTS AGE
app 2/2 Running 0 2s

READY 2/2: the native sidecar counts among the ready containers, along with app. The field that makes journal a native sidecar is read with jsonpath, an expression that extracts a specific field from the Pod:

Terminal window
kubectl get pod app -n sidecars -o jsonpath='{range .spec.initContainers[*]}{.name}{" => "}{.restartPolicy}{"\n"}{end}'
preparer =>
attendre-db =>
journal => Always

Only journal carries restartPolicy: Always. Now read what it relays. The sidecar starts before app, and the app.log file only exists once app has started: queried right away, journal answers that the file is missing. Wait ten seconds before reading:

Terminal window
sleep 10 && kubectl logs app -n sidecars -c journal --tail=3
15:57:28 requête traitée
15:57:31 requête traitée
15:57:34 requête traitée

After the ten-second wait, the command returns three lines in the HH:MM:SS requête traitée format, one every three seconds (the times are those of your run). Without the wait, it returns:

tail: can't open '/partage/app.log': No such file or directory

This message is not a failure: tail -F keeps retrying as long as the file does not exist. Compare with app, which does not write its requests to its output:

Terminal window
kubectl logs app -n sidecars -c app
config lue : mode=demo

logs -c app only shows the startup line, whereas logs -c journal shows the requests: that is the whole point of the sidecar, which brings to kubectl logs what the application writes to a file. One last read: without -c, kubectl logs does not refuse, it chooses.

Terminal window
kubectl logs app -n sidecars
Defaulted container "app" out of: app, preparer (init), attendre-db (init), journal (init)
config lue : mode=demo

The first line says which container was chosen (app, the first application container) and lists all the others, each init container suffixed (init), native sidecar included. The message is not an error: the logs that follow are those of app. To read another container, add -c.

When to choose an init container or a sidecar?

A single question settles it: does the task end? A task that ends before the application (waiting for a dependency, preparing a file, migrating data) is an init container. A task that runs as long as the application (relaying a log, refreshing a configuration, passing traffic through) is a sidecar, a native one preferably because Kubernetes guarantees its startup and shutdown order.

Sidecar use cases

Sidecars mostly serve to add a function to an application you do not want to modify: relay the logs of a file to the output or to a collector, synchronize a configuration from a repository, run a network proxy. The application does not know it exists, and a shared volume or localhost is enough to exchange data.

When to avoid a sidecar

Every added container consumes resources in every Pod, and a sidecar that crashes in a loop keeps the Pod from becoming ready. Avoid one when the application can write directly to its standard output, or when the task is the same for all the Pods of a node: a collection agent per node is deployed as a DaemonSet, not as a sidecar in every Pod.

Clean up the cluster

Deleting the namespace removes the Pod, the Deployment and the Service:

Terminal window
kubectl delete namespace sidecars
namespace "sidecars" deleted

The command took 42 seconds, for the same reason as the Pod deletion: the 30-second grace period.

Troubleshooting

The four symptoms of the lesson are read with the same commands: the state of the Pod, logs -c and describe.

SymptomLikely causeWhat to do
Init:1/2 that lastsAn init container is waiting or loopingkubectl logs <pod> -c <init> then kubectl describe pod
logs without -c does not show what you expectThe default container is app, not the sidecarRead the Defaulted container line and add -c
logs -c journal answers No such file or directory right after startupThe sidecar starts before the application has created the fileWait a few seconds
The Pod "app" is invalid ... may not add or remove containersAn existing Pod does not gain a containerDelete and recreate the Pod

Put it into practice

Two labs take up the two forms in the order of the lesson.

In the first, you create the application before its dependency: an init container must hold it back as long as the Service does not answer. You then create the dependency. The validation checks that the init container finished successfully and that the application moved to Running on its own, without you recreating it.

In the second, you declare a native sidecar (an init container with restartPolicy: Always) that follows, through a shared volume, the logs the application writes to a file. The validation checks the type of sidecar, the common volume and the application's writes, then that the sidecar does relay the lines written.

Key takeaways

  1. An init container runs and finishes before the application; init containers go one at a time, and each one must succeed.
  2. Init:1/2 means one init container out of two has finished; kubectl logs <pod> -c <name> reads the one that is running.
  3. A native sidecar is an init container with restartPolicy: Always: it starts before the application and stops after it.
  4. An ordinary init container accepts neither probes nor lifecycle; a native sidecar accepts them.
  5. Bound every wait with a number of attempts, and test what the application really needs, not just an open port.
  6. A shared emptyDir links the containers; it lives and disappears with the Pod.
  7. Without -c, kubectl logs chooses the default container and announces it with Defaulted container.
  8. You cannot add an init container to an existing Pod: you have to recreate the Pod with the new manifest.

Test your knowledge

This quiz covers the startup order, the difference between the sidecar pattern and the native sidecar, and reading the state of a Pod stuck in Init. Allow five minutes and aim for 80%; below that, reread "Differences between the two approaches".

Knowledge check

Check what you have learned with this interactive quiz

7 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer