Cloud Native 5 min read

Understanding Kubernetes InitContainers: How They Work and Share Data

This article explains the principles, common use cases, and data‑sharing techniques of Kubernetes initContainers, compares them with PostStart hooks, and provides complete YAML examples for fetching files before a main container starts and for waiting on dependent services.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Understanding Kubernetes InitContainers: How They Work and Share Data

1. How InitContainers Work

InitContainers run before the pod’s main containers and are used to perform pre‑startup tasks. They have two key characteristics:

Each initContainer must finish successfully; if it fails, Kubernetes restarts it until it succeeds.

InitContainers execute sequentially in the order defined, and a later one starts only after the previous one succeeds. If the pod’s restartPolicy is Never, a failure will prevent further restarts.

2. Common Use Cases

Providing tools or custom scripts that are not present in the main container image.

Delaying the start of the main container until required conditions are met, such as downloading files or waiting for external services.

3. Sharing Data Between InitContainer and Main Container

Scenario: The main container runs Nginx, but it needs the latest index.html before starting.

apiVersion: v1
kind: Pod
metadata:
  name: php-updated
spec:
  containers:
  - name: php
    image: php:7-fpm
    volumeMounts:
    - name: dir
      mountPath: /var/www/html/
  initContainers:
  - name: install
    image: busybox
    volumeMounts:
    - name: dir
      mountPath: /var/www/html/
    command:
    - wget
    - "-O"
    - "/var/www/html/index.php"
    - https://gitee.com
  volumes:
  - name: dir
    emptyDir: {}

After the pod starts, the initContainer downloads the file into the shared emptyDir volume, and the main PHP container can serve the generated index.html.

4. InitContainer vs. PostStart Hook

PostStart: Runs after the main container’s environment is created and does not necessarily execute before the container’s command.

InitContainer: Independent of the main container’s environment, can run with higher privileges and must complete before the main container starts. InitContainers do not support lifecycle, livenessProbe, readinessProbe, or startupProbe.

5. Example: Waiting for a Dependent Service

Requirement: The main container should start only after service myappb is available.

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    run: my-app
  name: my-app
spec:
  replicas: 2
  selector:
    matchLabels:
      run: my-app
  template:
    metadata:
      labels:
        run: my-app
    spec:
      restartPolicy: Always
      containers:
      - name: myapp-container
        image: busybox:1.28
        command: ['sh', '-c', 'echo The app is running! && sleep 3600']
      initContainers:
      - name: init-myappb
        image: busybox:1.28
        command: ['sh', '-c', "until nslookup myappb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myappb; sleep 2; done"]

Service definition used for the test:

apiVersion: v1
kind: Service
metadata:
  name: myappb
spec:
  ports:
  - protocol: TCP
    port: 80
    targetPort: 9377

Before the service is created, the initContainer remains in a waiting state, logging its status. Once the service exists, the initContainer detects it and the main container starts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Kubernetesservice discoveryPodInitContainer
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.