Google recommends that you do not run database schema updates in the app's startup code and instead run database schema updates on a separate cloud build step when deploying. See this YouTube video clip made by Google's official channel.
Run the database migrations by using the app-engine-exec-wrapper which is a "helper" for the Cloud SQL Auth Proxy. See the official documentation for more information and a example:
https://cloud.google.com/python/django/run#cloudbuild-automation
I was successfully able to run php artisan migrate --force
while deploying a Laravel app to a Cloud Run service by adding a extra 4th migration step mentioned above to the cloudbuild.yaml file. I was stuck on this for a while but found the above answers help point me in the right direction. I also found this post to be a helpful example and may be more useful if you are using NPM:
Run node.js database migrations on Google Cloud SQL during Google Cloud Build
Here is my entire cloudbuild.yaml file:
steps:
- name: gcr.io/cloud-builders/docker
args:
- build
- '--no-cache'
- '-t'
- '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
- .
- '-f'
- Dockerfile
id: Build
- name: gcr.io/cloud-builders/docker
args:
- push
- '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
id: Push
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk:slim'
args:
- run
- services
- update
- $_SERVICE_NAME
- '--platform=managed'
- '--image=$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
- >-
--labels=managed-by=gcp-cloud-build-deploy-cloud-run,commit-sha=$COMMIT_SHA,gcb-build-id=$BUILD_ID,gcb-trigger-id=$_TRIGGER_ID,$_LABELS
- '--region=$_DEPLOY_REGION'
- '--quiet'
id: Deploy
entrypoint: gcloud
- name: gcr.io/google-appengine/exec-wrapper
args:
- '-i'
- '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
- '-e'
- DB_CONNECTION=mysql
- '-e'
- 'DB_SOCKET=/cloudsql/$_DB_CONNECTION'
- '-e'
- DB_PORT=3306
- '-e'
- DB_DATABASE=$_DB_DATABASE
- '-e'
- DB_USERNAME=$_DB_USERNAME
- '-e'
- DB_PASSWORD=$_DB_PASSWORD
- '-s'
- '$_DB_CONNECTION'
- '--'
- php
- /app/artisan
- migrate
- '--force'
id: Migrate
waitFor:
- Build
- Push
- Deploy
timeout: 1200s
images:
- '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
options:
substitutionOption: ALLOW_LOOSE
tags:
- gcp-cloud-build-deploy-cloud-run
- gcp-cloud-build-deploy-cloud-run-managed
- prod_deployment