Skip to content
Latchkey

knex migrate:latest: Run Node Migrations in CI

knex migrate:latest runs every pending migration for the selected environment, recording them in the knex_migrations table.

Knex is a Node query builder with a migration CLI. migrate:latest is the deploy command; it reads the knexfile for connection and directory config.

What it does

knex migrate:latest runs each pending migration up() function in filename order and records it in knex_migrations. It uses a knex_migrations_lock table to prevent two processes migrating at once.

Common usage

Terminal
# uses knexfile.js, --env selects the config block
npx knex migrate:latest --env production

# explicit knexfile path
npx knex migrate:latest --knexfile ./db/knexfile.js --env production

Options

FlagWhat it does
--env <name>Which environment block in the knexfile to use
--knexfile <path>Path to the knexfile
--migrations-directory <dir>Override the migrations directory
--esmLoad ESM migration files

In CI

Set the connection via the --env block reading from process.env, so secrets stay out of the knexfile. Knex takes a lock via knex_migrations_lock, so concurrent runners serialize; a killed job can leave is_locked = 1, which you clear with knex migrate:unlock.

Common errors in CI

"Migration table is already locked" (from knex_migrations_lock) means a previous run did not release the lock; run knex migrate:unlock. "The migration directory is corrupt, the following files are missing" means a migration recorded as run is absent from disk, often a branch/rebase issue. "ECONNREFUSED" means the database is unreachable from the runner.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →