Init reads configuration, validates prerequisites, loads what is needed to serve, and either succeeds (releasing control to the main process) or fails (exiting non-zero).
The mechanism varies by context but the structure is uniform. Read configuration from environment variables, files, or a configuration server. Validate that the configuration is complete and consistent. Open the resources that must be available before serving: sockets, database connections, cache clients, queue subscriptions. Register with service discovery if the environment requires it. Signal readiness. Either release control to the main loop, or exit non-zero so the supervisor restarts the process.
graph TD
S[Start] --> R[Read config]
R --> V{Validate}
V -->|invalid| F[Exit non-zero]
V -->|valid| O[Open resources]
O --> G[Register / signal ready]
G --> M[Main loop]
F --> X[Supervisor restarts]
In systemd, init is organized as units. Each unit declares its dependencies, its startup command, its restart policy, and its target state. systemd computes a dependency graph and starts units in the right order, with parallel starts where the graph allows. In containers, init runs as PID 1 and is responsible for reaping zombies and forwarding signals: the container's PID 1 must forward SIGTERM to its child processes, or a graceful shutdown will hang until the orchestrator's grace period expires.
Writing a clean init
Read config first
Read environment variables and config files before doing anything else. Fail fast if required values are missing.
Validate before opening resources
Check that the database host resolves, the credentials parse, the schema version matches. Abort early if not.
Open resources, then signal readiness
Open the database pool, warm the cache, subscribe to queues. Only after all dependencies are ready, signal readiness to the orchestrator.
Forward signals to children
If PID 1 has children, forward SIGTERM and SIGINT. Reap zombies. On shutdown, close resources gracefully.
A common variation is the "init container" pattern in Kubernetes: a separate container runs before the main container, with the same filesystem volume, to perform initialization tasks that should complete before the main container starts (running migrations, copying config, waiting for a dependency). The main container starts only after every init container has exited successfully.