The deploy scaled to three replicas and half the rollout failed. One pod ran the migration, two hit a duplicate-column error, the Deployment never went healthy, and the migrations table claimed a batch had run that was only partly applied.
Running php artisan migrate from the container entrypoint is fine with one container. With three, you have asked Kubernetes to run your migration three times simultaneously and hoped MySQL would sort it out.
Reproduce the race before you fix it#
Start from the shape that breaks, because it is the shape most Laravel images ship with. The entrypoint runs migrations and then hands off to PHP-FPM, which is harmless on a single VPS and actively dangerous once replicas is greater than one. Every pod in the ReplicaSet starts at roughly the same moment against the same database.
#!/bin/sh
# docker/entrypoint.sh — the version that bites you at scale
set -e
php artisan migrate --force # every pod runs this
exec php-fpm
apiVersion: apps/v1
kind: Deployment
metadata:
name: app
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: registry.example.com/app:2026.11.30
command: ["/app/docker/entrypoint.sh"]
Roll that out and the pod logs tell the story — one winner, two casualties:
pod/app-7c9f4d8b6-2xk9p INFO Running migrations.
pod/app-7c9f4d8b6-2xk9p 2026_11_28_101500_add_status_to_orders ........ DONE
pod/app-7c9f4d8b6-hv4tn SQLSTATE[42S21]: Column already exists: 1060
pod/app-7c9f4d8b6-qm82d SQLSTATE[HY000]: Lock wait timeout exceeded
If you got here from a working single-container setup, the Dockerfile and pod wiring in dockerising a Laravel app for Kubernetes is the baseline the rest of this assumes.
Add --isolated to the migrate command#
--isolated is the one-line fix. Laravel acquires an atomic lock through the application's cache driver before it runs anything; the pods that fail to acquire it skip the migration entirely and exit with a successful status code, which is exactly what you want from a container that is about to serve traffic.
#!/bin/sh
set -e
php artisan migrate --force --isolated
exec php-fpm
The losers print a line and move on:
pod/app-7c9f4d8b6-hv4tn The [migrate] command is already running.
pod/app-7c9f4d8b6-qm82d The [migrate] command is already running.
If you would rather see the losers in your deploy output than have them silently succeed, pass a custom exit code. --isolated=12 makes every pod that did not get the lock exit 12 instead of 0:
php artisan migrate --force --isolated=12
Only use that where something is actually reading the exit code. In an entrypoint it means two of your three pods crash-loop, which is a worse outcome than the problem you started with.
Pick a cache driver that locks across pods#
This is the step that quietly undoes everything else. The lock lives in your cache store, so it is only distributed if the store is. Laravel supports isolation on the memcached, redis, dynamodb, database, file and array drivers — but file and array live inside the container. Three pods with CACHE_STORE=file means three separate filesystems, three locks, three winners, and the original race with an extra layer of confidence on top.
Use a store every pod reaches: Redis, Memcached, or the application database.
// config/cache.php
'default' => env('CACHE_STORE', 'redis'),
env:
- name: CACHE_STORE
value: redis
- name: REDIS_HOST
value: redis-master.default.svc.cluster.local
The database driver is the pragmatic choice if you do not want the migration to depend on Redis being up. It needs the cache and cache_locks tables to exist — which, on a first deploy, is itself a migration. Chicken, egg. Redis sidesteps that, and if you are moving off it for licensing reasons, the swap is covered in migrating a Laravel app from Redis to Valkey.
One more trap: the lock key is derived from the command name and prefixed per application, so two apps sharing a Redis instance with the same CACHE_PREFIX will block each other's migrations. Give each app its own prefix.
Move the migration out of the entrypoint and into a Job#
--isolated makes the entrypoint survivable. It does not make it correct. Every pod still connects, still tries, still waits on the lock before it starts serving — and the migration runs while new pods are coming up, which is the one ordering you did not want.
An init container is the first thing people reach for and it has the same flaw: init containers run once per pod, so a three-replica Deployment runs yours three times. Use one only if you genuinely cannot run a Job, and only with --isolated on.
A dedicated Job expresses the intent properly — run this once, to completion, before anything else.
apiVersion: batch/v1
kind: Job
metadata:
name: app-migrate-2026-11-30
spec:
backoffLimit: 0 # a failed migration should not be retried blindly
ttlSecondsAfterFinished: 86400
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: registry.example.com/app:2026.11.30 # pin to the release being deployed
command: ["php", "artisan", "migrate", "--force", "--isolated"]
envFrom:
- secretRef:
name: app-env
resources:
requests:
cpu: 200m
memory: 512Mi
limits:
memory: 1Gi
Three things earn their place there. The image tag is pinned to the release, not latest, so the Job runs the migrations that shipped with this build. backoffLimit: 0 stops Kubernetes re-running a migration that failed halfway — you want a human looking at that, not a retry loop. And --isolated stays on even though a Job runs once, because a retried or manually re-applied Job is still a second migrator.
Name the Job after the release. A Job is immutable once created, so reapplying the same name on the next deploy fails with a validation error rather than running.
Wire the Job to a Helm pre-upgrade hook#
If you deploy with Helm, the hook annotations give you the ordering for free: the Job runs and completes before Helm touches the Deployment, so the new pods never start against an unmigrated schema.
apiVersion: batch/v1
kind: Job
metadata:
name: {{ .Release.Name }}-migrate
annotations:
"helm.sh/hook": pre-install,pre-upgrade
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
command: ["php", "artisan", "migrate", "--force", "--isolated"]
before-hook-creation clears the previous release's Job so the immutable-name problem disappears. hook-succeeded tidies up after a clean run while leaving failed Jobs behind for you to read.
Watch the timeout. Helm waits for the hook to complete and helm upgrade defaults to five minutes, so a migration slower than that fails the release even though it is still running happily in the cluster. Pass --timeout 20m for the deploys you know are long.
Your old pods keep serving traffic throughout, which only works if their readiness probes are honest about what the app can do mid-migration — see Laravel health checks for Kubernetes readiness and liveness probes. Queue workers are the other population to think about: they are running the old code against the new schema for the length of the rollout, and if you scale them with KEDA, new workers can appear at any moment during it.
Clear the lock when a migrator dies mid-run#
Laravel releases the isolation lock in a finally block, so it survives a failed migration and a thrown exception. It does not survive a SIGKILL — an OOMKilled migrator or an evicted node leaves the lock sitting there, and the next deploy's migrate command politely decides someone else is already running and exits 0 without migrating anything. That is the failure mode to recognise: a green deploy with no schema change.
The lock expires on its own after one hour, and there is no CLI flag to shorten that. If an hour is longer than your deploy window — it usually is — override it on the command:
// app/Console/Commands/MigrateCommand.php
namespace App\Console\Commands;
use Carbon\CarbonInterval;
use Illuminate\Database\Console\Migrations\MigrateCommand as BaseMigrateCommand;
class MigrateCommand extends BaseMigrateCommand
{
/**
* How long the --isolated lock is held before it expires on its own.
*/
public function isolationLockExpiresAt(): CarbonInterval
{
return CarbonInterval::minutes(10);
}
}
Set it longer than your slowest migration and shorter than your deploy timeout. Too short and a long migration loses its own lock while still running; too long and a crashed migrator wedges every deploy until it expires.
To clear a stuck lock by hand, run a debug pod against the release image and force-release it. The key is framework/command-migrate, prefixed by your cache prefix:
kubectl run migrate-debug --rm -it --restart=Never \
--image=registry.example.com/app:2026.11.30 \
--overrides='{"spec":{"containers":[{"name":"migrate-debug","image":"registry.example.com/app:2026.11.30","envFrom":[{"secretRef":{"name":"app-env"}}],"stdin":true,"tty":true,"command":["php","artisan","tinker"]}]}}'
// inside tinker
Cache::lock('framework/command-migrate')->forceRelease();
Check before you clear. Force-releasing a lock that a live migrator still holds hands you the exact race you spent this article avoiding.
Keep the schema compatible with both versions of the code#
None of this makes the migration itself safe. The lock guarantees one migrator; it says nothing about the gap between the schema changing and every pod running the code that expects it. During a rolling update you have old pods and new pods talking to one schema, and a DROP COLUMN the old code still selects is an outage regardless of how cleanly it was locked.
That is the expand-and-contract problem, and it is the other half of this job — zero-downtime database migrations with the expand and contract pattern covers the nullable-expand, backfill and contract sequence in full. Get that right and the lock becomes what it should be: a guard against a duplicated migrator, not the thing holding your deploy together.
If you would rather not have two code versions live at once at all, blue-green deployments with an Nginx upstream switch trades infrastructure cost for a much simpler schema story. Either way, make the migration Job's logs land somewhere durable — ttlSecondsAfterFinished deletes the pod, and with it the only record of what your migration actually did.
FAQ#
How do I run Laravel migrations in Kubernetes?
Run them from a dedicated Job pinned to the image tag you are deploying, with php artisan migrate --force --isolated as the command and backoffLimit: 0. If you deploy with Helm, annotate that Job as a pre-install,pre-upgrade hook so it completes before the Deployment is updated. Running migrations from the container entrypoint works with one replica and races itself with more than one.
What does artisan migrate --isolated do?
It makes Laravel acquire an atomic lock through the application's cache driver before running any migrations. Any other migrate command that starts while that lock is held does not run, prints "The [migrate] command is already running", and still exits with a successful status code. You can pass a custom exit code instead with --isolated=12 if you want the skipped runs to be visible to your deploy tooling.
Should migrations run in an init container or a Job?
A Job, in almost every case. Init containers run once per pod, so a Deployment with three replicas runs your migration three times — --isolated makes that survivable but it is still the wrong shape, and the migration ends up running while new pods are already starting. A Job runs once to completion and, as a Helm pre-upgrade hook, runs before the new pods exist at all.
What happens if two pods run migrate at the same time?
Without --isolated, both read the same migrations table, both decide the same files are pending, and both start executing them. You get duplicate-column errors, lock-wait timeouts, or a partly applied batch recorded as complete — and the Deployment goes unhealthy because the losing pods exited non-zero. With --isolated and a shared cache store, only one pod migrates and the others exit cleanly.
Which cache drivers support --isolated?
Laravel supports isolation on the memcached, redis, dynamodb, database, file and array drivers. In Kubernetes only the first four are useful: file and array are local to each container, so every pod acquires its own lock and nothing is actually coordinated. Every pod must also point at the same cache instance and share a cache prefix for the lock to mean anything.
How long does the migrate isolation lock last?
One hour by default, and there is no command-line flag to change it. Laravel releases the lock in a finally block, so a failed or erroring migration still frees it — but a pod that is OOMKilled or evicted leaves the lock in place until it expires. Override isolationLockExpiresAt() on a subclass of MigrateCommand to set something closer to your deploy window.