2

I'm running a Laravel app on multiple servers at the same time. It's running in a Docker image. Each time I deploy some code changes, Docker image is restarted and then it runs after_deployment.sh script which contains php artisan migrate --force. This script is executed by ALL of my servers, not just one.

All servers use the same central DB. So if two servers try to run the php artisan migrate at roughly the same time, only the first server succeeds, the other fails somewhere in the middle and logs an error. This is not great.

There was a similar problem with running cronjobs (Laravel Scheduler) on just one server, but that is now solved as Laravel provides the ->onOneServer(); method for Scheduled jobs.

Is there something similar for running migrations on just one server? Something like php artisan migrate --force --on-one-server?

Boring person
  • 443
  • 1
  • 5
  • 12

1 Answers1

0

Starting from Laravel 9.38, you have the php artisan migrate --isolated that will acquire an atomic lock before running the migrations.
From the Doc:

When the isolated option is provided, Laravel will acquire an atomic lock using your application's cache driver before attempting to run your migrations. All other attempts to run the migrate command while that lock is held will not execute; however, the command will still exit with a successful exit status code

Please note that you cache driver should be set to one of the following:
memcached, redis, dynamodb, database, file, or array

ml59
  • 1,495
  • 1
  • 9
  • 10