DevOps & CI/CD

Zero-Downtime Schema Changes with Knex.js Migrations in CI/CD

Schema changes cause a large share of deployment incidents. A migration is forgotten and the new code queries a column that doesn't exist. A migration runs, but the old code still serving traffic breaks against the new schema. Or an ALTER TABLE waits on a lock and every query behind it queues up.

Automating migrations in CI/CD fixes the first problem. The other two need migrations designed so that the old and new versions of your application can both run against the schema at the same time. This guide covers both, using Node.js, Knex.js and PostgreSQL with GitHub Actions.

The Pitfalls of Manual Database Management

Before we dive into the solution, let’s briefly touch upon why manual database management is such a risk, especially at scale:

  • Human Error: Forgetting to run a script, running the wrong script, or running scripts in the wrong order are all common mistakes that can cripple a system.
  • Schema Drift: Changes applied by hand to one environment but not another (for example, a hotfix ALTER TABLE run on production but never added to staging) make every later deployment unpredictable.
  • Downtime Risk: Applying migrations manually, especially large ones, often requires taking the application offline, leading to unacceptable service interruptions.
  • Lack of Version Control: Without proper automation, tracking which migration has been applied to which environment can be opaque, making rollbacks or audits difficult.

Integrating Knex.js Migrations into Your CI/CD Pipeline

Our goal is to ensure that every code change that involves a database schema modification is automatically validated and applied as part of the CI/CD process, minimizing human intervention and maximizing reliability.

Step 1: Set Up Your Node.js Project with Knex.js

First, you need a Node.js project configured to use Knex.js. If you don't have one, here's a quick setup. We'll use PostgreSQL as our database, but Knex.js supports many others.

Bash
npm init -y
npm install knex pg
npx knex init

This creates a knexfile.js in your root directory. This file is crucial as it defines your database connections for different environments. Here’s an example knexfile.js configuration, with environment variables for sensitive data:

JavaScript
// knexfile.js
const path = require('path');

module.exports = {
  development: {
    client: 'pg',
    connection: {
      host: process.env.DB_HOST || 'localhost',
      port: process.env.DB_PORT || 5432,
      user: process.env.DB_USER || 'your_user',
      password: process.env.DB_PASSWORD || 'your_password',
      database: process.env.DB_NAME || 'your_dev_db',
    },
    migrations: {
      directory: path.join(__dirname, 'db', 'migrations'),
      tableName: 'knex_migrations',
    },
    seeds: {
      directory: path.join(__dirname, 'db', 'seeds'),
    },
  },

  test: {
    client: 'pg',
    connection: {
      host: process.env.TEST_DB_HOST || 'localhost',
      port: process.env.TEST_DB_PORT || 5433, // Use a different port for test DB
      user: process.env.TEST_DB_USER || 'test_user',
      password: process.env.TEST_DB_PASSWORD || 'test_password',
      database: process.env.TEST_DB_NAME || 'your_test_db',
    },
    migrations: {
      directory: path.join(__dirname, 'db', 'migrations'),
      tableName: 'knex_migrations',
    },
    seeds: {
      directory: path.join(__dirname, 'db', 'seeds'),
    },
  },

  production: {
    client: 'pg',
    connection: {
      host: process.env.PROD_DB_HOST,
      port: process.env.PROD_DB_PORT,
      user: process.env.PROD_DB_USER,
      password: process.env.PROD_DB_PASSWORD,
      database: process.env.PROD_DB_NAME,
      // Verify the server certificate; pass your provider's CA bundle if needed
      ssl: { rejectUnauthorized: true, ca: process.env.PROD_DB_CA_CERT },
    },
    migrations: {
      directory: path.join(__dirname, 'db', 'migrations'),
      tableName: 'knex_migrations',
    },
    seeds: {
      directory: path.join(__dirname, 'db', 'seeds'),
    },
  },
};

Create your first migration: npx knex migrate:make create_users_table. This will create a file in db/migrations (or wherever your migrations.directory points).

JavaScript
// db/migrations/YYYYMMDDHHMMSS_create_users_table.js
exports.up = function(knex) {
  return knex.schema.createTable('users', function(table) {
    table.increments('id');
    table.string('username', 255).notNullable().unique();
    table.string('email', 255).notNullable().unique();
    table.string('password_hash', 255).notNullable();
    table.timestamps(true, true);
  });
};

exports.down = function(knex) {
  return knex.schema.dropTable('users');
};

Step 2: Know What Knex Guarantees, and What It Doesn't

  • Each migration runs once: Knex records applied migrations in the knex_migrations table, and knex_migrations_lock stops two deploys from running migrations at the same time.
  • Migrations are transactional on PostgreSQL: each migration runs inside a transaction by default, so a failure rolls back that migration's changes. MySQL can't roll back DDL statements, so a failed migration there can leave a half-applied schema.
  • Knex doesn't check that a change is safe to run under load. That depends on how you write the migration (Step 5).

Set a lock timeout at the start of migrations that alter busy tables. If the ALTER can't get its lock quickly, it fails and can be retried, instead of blocking every other query on the table while it waits:

JavaScript
exports.up = async function (knex) {
  await knex.raw("SET LOCAL lock_timeout = '5s'");
  await knex.schema.alterTable('users', (table) => {
    table.string('display_name', 255).nullable();
  });
};

Step 3: Integrate into Your CI Pipeline

The Continuous Integration (CI) stage is where we validate our code and our migrations. We want to ensure that new migrations can be applied successfully against a clean or known-state database before any application tests run. Let's use GitHub Actions as an example.

YAML
# .github/workflows/ci.yml
name: Node.js CI with DB Migrations

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]

jobs:
  build:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_DB: your_test_db
          POSTGRES_USER: test_user
          POSTGRES_PASSWORD: test_password
        ports:
          - 5433:5432 # Map container port 5432 to host port 5433
        options: >- # Health check to ensure DB is ready
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
    - uses: actions/checkout@v4
    - name: Use Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '22'

    - name: Install dependencies
      run: npm ci

    - name: Run Database Migrations (Test Environment)
      env:
        TEST_DB_HOST: localhost
        TEST_DB_PORT: 5433
        TEST_DB_USER: test_user
        TEST_DB_PASSWORD: test_password
        TEST_DB_NAME: your_test_db
      run: npx knex --knexfile knexfile.js migrate:latest --env test

    - name: Check that down migrations work
      env:
        TEST_DB_HOST: localhost
        TEST_DB_PORT: 5433
        TEST_DB_USER: test_user
        TEST_DB_PASSWORD: test_password
        TEST_DB_NAME: your_test_db
      run: |
        npx knex --knexfile knexfile.js migrate:rollback --all --env test
        npx knex --knexfile knexfile.js migrate:latest --env test

    - name: Run application tests
      run: npm test

In this CI workflow:

  1. GitHub Actions starts a PostgreSQL service container and waits for its health check to pass before running the steps, so no sleep is needed.
  2. We configure Knex.js to use this test environment.
  3. Crucially, we run npx knex migrate:latest --env test. This applies all pending migrations to our clean test database. If a migration fails, the CI build fails immediately, alerting us to issues before they hit production.
  4. Rolling everything back and migrating again catches broken down functions before you need one in an emergency.
  5. After successful migration, we run our application tests. These tests now run against a database that has the latest schema, ensuring our application logic and the database schema are compatible.

⚠️ Common Mistake: Many teams skip running migrations in CI, relying solely on local development or CD. This means migration failures are only caught much later in the pipeline, increasing the cost of fixing them and potentially impacting staging or even production environments.

Step 4: Integrate into Your CD Pipeline (Deployment)

For Continuous Deployment (CD), the strategy is similar but targets your actual staging or production database. The key is to run the migrations before your new application code is deployed and brought online. This prevents scenarios where new code expects a schema change that hasn't been applied yet.

YAML
# .github/workflows/cd.yml (partial example for deployment)
name: Deploy to Production

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production # Use GitHub Environments for protected deployments and secrets

    steps:
    - uses: actions/checkout@v4
    - name: Use Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '22'

    - name: Install dependencies
      run: npm ci

    - name: Run Database Migrations (Production Environment)
      env:
        PROD_DB_HOST: ${{ secrets.PROD_DB_HOST }}
        PROD_DB_PORT: ${{ secrets.PROD_DB_PORT }}
        PROD_DB_USER: ${{ secrets.PROD_DB_USER }}
        PROD_DB_PASSWORD: ${{ secrets.PROD_DB_PASSWORD }}
        PROD_DB_NAME: ${{ secrets.PROD_DB_NAME }}
        PROD_DB_CA_CERT: ${{ secrets.PROD_DB_CA_CERT }}
      run: npx knex --knexfile knexfile.js migrate:latest --env production

    - name: Deploy Application (e.g., to Kubernetes, VM, serverless)
      run: | # Replace with your actual deployment command
        echo "Deploying application version $GITHUB_SHA to production..."
        # kubectl apply -f kubernetes_manifests/
        # scp -r dist/ user@server:/app/
        # pm2 reload app

Key considerations for CD:

  • Order of operations: migrations run before the new code is deployed, so the new code never starts against an old schema. During the rollout, though, the old code is still serving traffic against the new schema. That's only safe if every migration is backward compatible, which is what the next step is about.
  • Security: Production database credentials should never be hardcoded. Use your CI/CD system's secret management (e.g., GitHub Actions Secrets, HashiCorp Vault, AWS Secrets Manager).
  • Environment-Specific Configuration: Ensure your knexfile.js correctly differentiates between production and other environments, potentially having stricter connection settings or SSL requirements.

Step 5: Make Breaking Changes in Several Deploys (Expand and Contract)

A change that removes or renames something the running code depends on can't be done in one deploy without breaking requests. Split it into steps that are each safe on their own. Renaming users.name to users.full_name looks like this:

  1. Expand: add full_name as a nullable column. Deploy code that writes to both columns and still reads name.
  2. Backfill: copy existing values in batches (UPDATE ... WHERE id BETWEEN ...), not in one statement that locks and rewrites the whole table.
  3. Switch reads: deploy code that reads full_name.
  4. Contract: once no running code uses name, drop it in a later migration.

The same pattern applies to dropping columns (stop using it first, drop it a release later), adding NOT NULL (backfill first, then add a CHECK ... NOT VALID constraint and validate it separately), and building indexes on large PostgreSQL tables (CREATE INDEX CONCURRENTLY). Knex wraps migrations in a transaction, and CONCURRENTLY can't run inside one, so set exports.config = { transaction: false } in that migration.

💡 Tip: Review migration files with the same care as application code. A short checklist for reviewers ("does this lock a large table? can the currently deployed code still run against it?") catches most risky changes before they ship.

Actionable Takeaways

  1. Adopt a Migration Tool: If you're not already using one, integrate a dedicated database migration tool like Knex.js, Alembic (Python), Flyway (Java), or Laravel Migrations. These tools provide version control, transactional safety, and a clear path for schema evolution.
  2. Test Migrations in CI: Set up your CI pipeline to run all pending migrations against a temporary or test database. This catches schema errors early, before they can impact production.
  3. Keep every migration backward compatible: split renames, drops and new constraints into expand-and-contract steps across several deploys, and set a lock_timeout on migrations that alter busy tables.
  4. Automate in CD, Before Deployment: Configure your CD pipeline to execute migrate:latest on your target database before deploying the new application code. This ensures schema readiness and prevents application startup failures.
  5. Secure Your Database Credentials: Store all production database credentials in your CI/CD system's secret manager, never in plain text or source control. Pass them as environment variables during migration execution.
Advertisement