EC2: Laravel migrations run as many times as the instances

Viewed 595

We experience a very weird issue at the moment. Our tech stack involves AWS Elastic Beanstalk,EC2 and Laravel deploying the code with Bitbucket Pipelines.

The problem is that whenever we include a migration in the deploy then it's run twice (as many times as our EC2 instances in this environment!).

Our scripts are located under .ebextensions dir:

option_settings:
  "aws:elasticbeanstalk:container:php:phpini":
    document_root: /public
container_commands:
    01initdb:
        command: "php artisan migrate"

We ended up breaking our deploy a few times because the system can't tell that this migration has already run.

Anyone saw this issue before?

Update We came up with this implementation as MySQL connection is refused if we add php artisan migrate in the build script.

1 Answers

There are many ways to do this:

  1. Have a single ops server run all the tasks that need to be run on only 1 server. Your bitbucket pipeline can trigger this ops server for single server tasks and the others for multi-server tasks.
  2. Create a custom Artisan command that attains locks (DB or cache) to run migrations while avoiding parallel runs / race conditions.
  3. Trigger deployments serially (dont know if that's possible on Beanstalk).
  4. As the OP mentioned, setting the leader_only: true flag on Elastic Beanstalk scripts to only run the command on a single instance does the trick!
Related