Search code examples
phplaraveldockergoogle-cloud-sqlgoogle-cloud-run

Running Laravel migrations to Cloud SQL part of continous deployment


I'm working on a Laravel project with fully continuous deployments to Cloud Run and using Cloud SQL as storage service. Right now, I need to perform php artisan migrate manually using the cloud_sql_proxy within the local environment.

Does anyone know whether it is possible to perform this step automatically, possibly part of the Dockerfile.

This is my current Dockerfile:

FROM php:7

ENV PORT=8080
ENV HOST=0.0.0.0

RUN apt-get update -y \
  && apt-get install --no-install-recommends -y openssl zip unzip git libonig-dev \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*

RUN ["/bin/bash", "-c", "set -o pipefail && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer"]
RUN docker-php-ext-install pdo mbstring
WORKDIR /app
COPY . /app
RUN composer validate && composer install

EXPOSE 8080
CMD ["php", "artisan", "serve", "--host=0.0.0.0", "--port=8080"]

Thanks for any help!


Solution

  • It's not recommended to put in Dockerfile the migration script as that will be triggered for EVERY future requests. You need to run it only ONCE and that execution should be triggered by a build script or by a developer.

    For migrations that introduce breaking changes either on commit or on rollback, it's mandatory to have a full stop, and of course, rollback planned accordingly.

    Also pay attention, that a commit/push should not trigger immediately the new migrations. Often these are not part of the regular CI/CD pipeline that goes to production.

    Make sure you have a manual deploy for migrations and not under CI/CD.

    After you deploy a service, you can create a new revision and assign a tag that allows you to access the revision at a specific URL without serving traffic.

    A common use case for this, is to run and control the first visit to this container. You can then use that tag to gradually migrate traffic to the tagged revision, and to rollback a tagged revision.

    To deploy a new revision of an existing service to production:

    gcloud beta run deploy myservice --image IMAGE_URL  --no-traffic --tag TAG_NAME
    

    The tag allows you to directly test(or run via this the migration - the very first request) the new revision at a specific URL, without serving traffic. The URL starts with the tag name you provided: for example if you used the tag name green on the service myservice, you would test the tagged revision at the URL https://green---myservice-abcdef.a.run.app