Connect MySQL Database with Laravel and Google Cloud Run

Before following this tutorial, make sure you have created a MySQL database instance, if you haven't done it yet, I recommend this tutorial about ┬┐How to Create a MySQL Instance on Google Cloud?

Unix Socket Connection

Since our docker container in Cloud Run does not have a database, we must establish a connection between processes or a Unix Socket Connection.

Luckily, in laravel this process is as simple as creating an environment variable with the connection path and inform to our Cloud Run service that we are using the database through a unix socket conection.

In the next section we are going to establish this type of connection.

Enviroment Variable DB_SOCKET

In our Cloud Run service we are going to create a variable called DB_SOCKET, which will contain the name of our database connection along with the /cloudsql/ prefix.

Enviroment Variable for Cloud SQL
Enviroment Variable for Cloud SQL

This name or value can be found in the main menu of your database as shown in the following image.

Cloud SQL Connection Name
Cloud SQL Connection Name

Once the variable is added, we will inform to our service about the Cloud SQL connection that we need.

Cloud SQL Connection

To establish this connection we must go to the Connections section of the Cloud Run service and in SQL Connections add the database from which we have taken the value.

Cloud SQL Connection to Cloud Run
Cloud SQL Connection to Cloud Run

Save and Restart the Service

Once you have added the conection name and established the unix socket connection, you must save the changes and wait for a new version of the service to be automatically generated with the new changes that will make than your laravel application can use the Cloud SQL Database.