🎓 A1Learner
🔍
0 of 51 lessons completed

Kubernetes: Multi-Container Pods and Init Containers

A multi-container Pod is a Pod that holds two or more containers. An init container is a container that runs first, finishes its one job, and then stops.

One Pod, three containers

The init container writes a file. The web container then serves pages. The helper container handles logs. emptyDir is storage that lives only as long as the Pod, taught in full in lesson 32.

apiVersion: v1
kind: Pod
metadata:
  name: web-pod
spec:
  initContainers:
  - name: setup
    image: nginx:1.27-alpine
    command: ["sh", "-c", "echo ready > /shared/ready.txt"]
    volumeMounts:
    - name: shared
      mountPath: /shared
  containers:
  - name: web
    image: nginx:1.27-alpine
    volumeMounts:
    - name: shared
      mountPath: /shared
  - name: log-helper
    image: nginx:1.27-alpine
  volumes:
  - name: shared
    emptyDir: {}

Both main containers are ready

2/2 counts the two main containers. The init container has already finished, so it is not counted.

kubectl get pods

Read one container at a time

The -c flag names one container. Without it, logs picks the first container only.

kubectl logs web-pod -c log-helper

Example

kubectl apply -f web-pod.yaml
kubectl get pods
kubectl logs web-pod -c log-helper

Key points

  • Sidecar: a helper container in the same Pod as the main container.
  • Use a sidecar to add logging or a sync helper to a Pod.
  • Init container: a container that runs to completion before the main containers start.
  • Use an init container to prepare files or wait for a service before the app starts.
  • Containers in one Pod share storage, so a sidecar can read the files the app writes.
  • Use kubectl logs -c to read the logs of one named container in a Pod.

In this example, apply creates a Pod with a web container and a log helper. get pods shows 2/2 ready. logs with -c reads the helper container alone. The init container ran first, then the two main containers started together.

Note

Keep the main container in charge of the app, and keep helpers small and single purpose.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

When does an init container run?