How to simulate a database migration init container mock in Python

A mock init container that runs environment checks and a staged database migration job before the main application starts, printing progress to stdout.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 15 views 0 copies

Python code

54 lines
Python 3.9+
```python
class MigrationJob:
    def __init__(self, name, steps):
        self.name = name
        self.steps = steps
        self.current_step = 0
        self.status = "pending"

    def run(self):
        print(f"Initializing migration job: {self.name}")
        for step in self.steps:
            self.current_step += 1
            self.status = "running"
            print(f"  Step {self.current_step}/{len(self.steps)}: {step}")
            self._execute_step(step)
        self.status = "completed"
        print(f"Migration job {self.name} completed successfully.")

    def _execute_step(self, step):
        required_actions = {
            "schema": "Creating schema",
            "data": "Migrating data",
            "index": "Building indexes",
            "seed": "Seeding initial data",
            "validate": "Validating integrity"
        }
        action = required_actions.get(step, "Executing")
        print(f"    -> {action}...")

    def rollback(self):
        self.status = "rolled_back"
        print(f"Migration job {self.name} rolled back.")


def init_container():
    """Mock init container that runs migration checks before main app starts."""
    print("--- Init Container Starting ---")
    env_checks = ["DB_HOST", "DB_PORT", "DB_NAME", "DB_USER"]
    
    for var in env_checks:
        print(f"Checking environment variable: {var}")
    
    migration = MigrationJob("db_v1_to_v2", ["schema", "data", "index", "seed", "validate"])
    migration.run()
    
    if migration.status == "completed":
        print("--- Init Container Finished: Ready for main container ---")
    else:
        print("--- Init Container Failed: Aborting start ---")
        raise SystemExit(1)


if __name__ == "__main__":
    init_container()

Output

stdout
--- Init Container Starting ---
Checking environment variable: DB_HOST
Checking environment variable: DB_PORT
Checking environment variable: DB_NAME
Checking environment variable: DB_USER
Initializing migration job: db_v1_to_v2
  Step 1/5: schema
    -> Creating schema...
  Step 2/5: data
    -> Migrating data...
  Step 3/5: index
    -> Building indexes...
  Step 4/5: seed
    -> Seeding initial data...
  Step 5/5: validate
    -> Validating integrity...
Migration job db_v1_to_v2 completed successfully.
--- Init Container Finished: Ready for main container ---

How it works

The init_container function acts as a lightweight stand-in for a Kubernetes init container, running critical checks before the main workload starts. The MigrationJob class encapsulates each migration step with a status tracker, allowing you to mock lifecycle behavior (pending → running → completed). _execute_step maps named steps to human-readable actions, making the progress output easy to follow. Because the simulation uses only print calls, you can adapt it into real orchestration code by replacing the mock actions with actual database queries or tool invocations. Checking migration.status == "completed" before exiting mirrors the gating logic init containers use to block pod startup on failure.

Common mistakes

  • Hardcoding environment variable names instead of reading them from `os.environ` in a real container
  • Using `raise SystemExit(1)` only for failure while forgetting to handle partial migration rollback in production
  • Not abstracting `_execute_step` to actually run SQL or invoke a migration tool like Alembic

Variations

  1. Replace `print` calls with `logging` module to capture structured logs in a real init container image
  2. Use `os.getenv("DB_HOST")` and validate each variable actually exists rather than merely printing its name

Real-world use cases

  • Simulating an init container that waits for a database schema to be ready before deploying an app pod in Kubernetes.
  • Testing CI/CD pipelines locally to verify migration steps run before the application container boots.
  • Teaching teams how init container phases gate the start of the main service in a microservices architecture.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.