Init Containers
Kubernetes
MySQL
Container Orchestration
DevOps

How to use an init container to check if MySQL is ready for connections?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In Kubernetes, application pods often start faster than database dependencies. If MySQL is still initializing, applications may crash or enter noisy retry loops at boot. An init container can enforce startup ordering by blocking the main container until MySQL is truly usable.

Core Sections

1. Why init containers are better than startup sleep hacks

A fixed sleep in app startup scripts is fragile because database startup time changes with load, storage speed, and recovery events. Init containers provide explicit dependency gating:

  • they run before app containers
  • they must complete successfully
  • failures are visible in pod status

This gives a deterministic startup contract. Instead of app logs full of transient connection errors, you get a clear init-stage signal that dependency is unavailable.

2. Build a readiness check that matches real app requirements

Checking only TCP connectivity is often too weak. A port can be open while authentication or schema migration is still incomplete. For many workloads, a query-level check is more accurate.

Example init container with bounded retry and SELECT 1:

yaml
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4  name: orders-api
5spec:
6  replicas: 1
7  selector:
8    matchLabels:
9      app: orders-api
10  template:
11    metadata:
12      labels:
13        app: orders-api
14    spec:
15      initContainers:
16        - name: wait-for-mysql
17          image: mysql:8.0
18          command:
19            - sh
20            - -c
21            - |
22              for i in $(seq 1 90); do
23                mysql -h "$MYSQL_HOST" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SELECT 1" && exit 0
24                echo "mysql not ready, attempt $i"
25                sleep 2
26              done
27              echo "mysql unavailable after timeout" >&2
28              exit 1
29          env:
30            - name: MYSQL_HOST
31              value: mysql.default.svc.cluster.local
32            - name: MYSQL_USER
33              valueFrom:
34                secretKeyRef:
35                  name: mysql-app-credentials
36                  key: username
37            - name: MYSQL_PASSWORD
38              valueFrom:
39                secretKeyRef:
40                  name: mysql-app-credentials
41                  key: password
42      containers:
43        - name: orders-api
44          image: myorg/orders-api:1.12.0

This approach fails fast and visibly if dependency never becomes ready.

3. Keep retries bounded and observable

An unbounded until loop can hide real outages and block rollouts indefinitely. Use a finite retry budget and explicit exit code. Also print attempt numbers so logs tell you how long startup waited.

Helpful operational rule:

  • short retries for transient cold starts
  • clear timeout for persistent failures
  • alerting on repeated init failures

This keeps incidents visible instead of silently stuck.

4. Separate dependency checks from app health probes

Init checks and probes solve different problems:

  • init container: dependency readiness before startup
  • readiness probe: app can serve traffic now
  • liveness probe: app should be restarted if unhealthy

Do not drop readiness probes just because init container exists. After startup, app can still fail due to downstream issues, config drift, or memory pressure.

5. Handle credentials and least privilege

Never embed database secrets directly in manifests or shell scripts committed to source control. Reference Kubernetes Secret keys and use a low-privilege MySQL user dedicated to readiness checks.

For a simple query check, user permissions can usually be minimal. Restricting privilege reduces blast radius if credentials leak through logs or misconfiguration.

6. Debugging failed init containers

When a pod stays in Init state, inspect events and init logs first:

bash
kubectl describe pod orders-api-xxxxx
kubectl logs pod/orders-api-xxxxx -c wait-for-mysql

Common failure causes:

  • wrong service hostname
  • wrong credentials
  • DNS resolution failures
  • NetworkPolicy blocking traffic

Because init logic is isolated, these failures are easier to diagnose than app-level retry noise.

7. Advanced pattern: combine init with migration jobs

If your app also requires schema migrations, run migrations as a separate Job and make app deployment depend on Job success. Keep init container focused on availability checks only. This avoids mixing two concerns in one startup script and prevents long-running schema operations from hiding as readiness checks.

Common Pitfalls

  • Using fixed sleep delays instead of real dependency checks.
  • Running infinite retry loops that conceal prolonged outages.
  • Checking only open port when authenticated query is required.
  • Hardcoding database credentials in deployment manifests.
  • Assuming init checks replace readiness and liveness probes.

Summary

  • Init containers are the right place to gate startup on MySQL availability.
  • Use query-level checks when your app needs authenticated DB access.
  • Keep retries bounded with explicit failure to improve observability.
  • Preserve secret hygiene and least-privilege database users.
  • Combine init checks with proper probes for stable runtime behavior.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design