Multi-Container Pods: Init containers

Learn about Init containers and multi-container Pods.

We'll cover the following

Init containers are a special type of container defined in the Kubernetes API. We run them in the same Pod as application containers, but Kubernetes guarantees they’ll start and complete before the main app container starts. It also guarantees they’ll only run once.

The purpose of init containers is to prepare and initialize the environment so it’s ready for application containers.

Consider a couple of quick examples.

We have an application that should only start when a remote API is accepting connections. Instead of complicating the main application with the logic to check the remote API, we run that logic in an init container in the same Pod. When we deploy the Pod, the init container comes up first and sends requests to the remote API waiting for it to respond. While this is happening, the main app container cannot start. However, as soon as the remote API accepts a request, the init container completes, and the main app container will start.

Assume we have another application that needs a one-time clone of a remote repository before starting. Again, instead of bloating and complicating the main application with the code to clone and prepare the content (knowledge of the remote server address, certificates, auth, file sync protocol, checksum verifications, etc.), we implement that in an init container that is guaranteed to complete the task before the main application container starts.

A drawback of init containers is that they’re limited to running tasks before the main app container starts. For something that runs alongside the main app container, we need a sidecar container.

Multi-container Pods: Sidecars

Sidecar containers are regular containers that run at the same time as application containers for the entire lifecycle of the Pod.

Unlike init containers, sidecars are not a resource in the Kubernetes API — we’re currently using regular containers to hack the sidecar pattern. Work is in progress to formalize the sidecar pattern in the API, but at the time of writing, it’s still an early alpha feature.

The job of a sidecar container is to add functionality to an app without having to implement it in the actual app. Common examples include sidecars that scrape logs, sync remote content, broker connections, and munge data. They’re also heavily used by services meshes where the sidecar intercepts network traffic and provides traffic encryption and telemetry.

Get hands-on with 1400+ tech skills courses.