Init Container Example
Download the YAML configuration file for the Init container example
Create the Deployment
Applies the configuration from the YAML file to create the pod with an Init container.
Check Pod Status
Wait for the main pod to come up and check its status.
Connect to the Nginx Container
Opens a bash shell inside the running Nginx container.
Test the Webpage
Hit the default webpage. It should be the one downloaded by the Init container from http://info.cern.ch.
Exit the Container
Exit the bash shell and return to your local terminal.
Cleanup
Deletes all resources defined in the YAML configuration file.
YAML Configuration File
apiVersion: v1
kind: Pod
metadata:
name: init-demo
spec:
containers:
- name: nginx
image: nginx
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 250m
memory: 256Mi
ports:
- containerPort: 80
volumeMounts:
- name: workdir
mountPath: /usr/share/nginx/html
initContainers:
- name: install
image: busybox
command:
- wget
- "-O"
- "/work-dir/index.html"
- http://info.cern.ch
volumeMounts:
- name: workdir
mountPath: "/work-dir"
volumes:
- name: workdir
emptyDir: {}
YAML Configuration Explanation:
Pod Structure:
- apiVersion: v1 → Specifies the Kubernetes API version
- kind: Pod → Defines this as a Pod resource
- metadata.name: init-demo → Names the pod "init-demo"
Main Container (nginx):
- image: nginx → Uses the official Nginx image
- resources → Defines CPU and memory requests/limits
- containerPort: 80 → Exposes port 80 for web traffic
- volumeMounts → Mounts the shared volume to /usr/share/nginx/html
Init Container (install):
- image: busybox → Uses a lightweight BusyBox image
- command → Runs wget to download a file
- - "wget" "-O" "/work-dir/index.html" "http://info.cern.ch" → Downloads the first website to the shared volume
- volumeMounts → Mounts the same shared volume to /work-dir
Shared Volume:
- name: workdir → Names the volume "workdir"
- emptyDir: {} → Creates an empty directory that's shared between containers
- The Init container writes to this volume, and the main Nginx container reads from it
How It Works:
The Init container runs first and downloads the content from http://info.cern.ch (the first website) into the shared volume. After the Init container completes successfully, the main Nginx container starts and serves the downloaded content. This demonstrates how Init containers can perform setup tasks before the main application starts.