Search code examples
laravelgoogle-cloud-sqlgoogle-cloud-run

How do I connect to Cloud SQL from a Laravel project running on Cloud Run?


for a proof of concept project, I'm trying to connect my Laravel project running on a fully-managed Cloud Run with Cloud SQL as storage layer.

I've managed to get a functioning service through Google App Engine using the gcloud app engine command (this service could connect to the storage layer). I've also connected successfully with the storage layer through a cloud_sql_proxy and a local docker container of my service. But I can't manage to get a setup working remotely with Cloud Run.

I'm deploying the docker image as follows:

gcloud run deploy --image eu.gcr.io/demo/customerservice --add-cloudsql-instances demo:europe-west1:dps-demo --update-env-vars INSTANCE_CONNECTION_NAME="demo:europe-west1:dps-demo

The error my service returns for requests is:

could not find driver (SQL: select * from `cache` where `key` = laravel_cachefa9d927c88ff8ebffd06913d97f9d59e limit 1)

(This error happens for any type of database queries and is similar if I'm using a local cache)

This is my .env file (I removed some clutter unrelated to the problem):

APP_NAME=Laravel
APP_ENV=local
APP_KEY=***
APP_DEBUG=true
APP_URL=http://CustomerService.test
APP_STORAGE=/tmp


LOG_CHANNEL=stack
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=***
DB_SOCKET=/cloudsql/demo:europe-west1:dps-demo

BROADCAST_DRIVER=log
CACHE_DRIVER=database
QUEUE_CONNECTION=sync
SESSION_DRIVER=database
SESSION_LIFETIME=120

VIEW_COMPILED_PATH=/tmp

Solution

  • Make sure the container has the relevant php/mysql/pdo modules enabled.

    Your DB config should be similar to this:

     'mysql' => [
                'driver' => 'mysql',
                'database' => env('DB_DATABASE', 'forge'),
                'username' => env('DB_USERNAME', 'forge'),
                'password' => env('DB_PASSWORD', ''),
                'unix_socket' => env('DB_SOCKET', ''),
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix' => '',
                'prefix_indexes' => true,
                'strict' => true,
                'engine' => null,
                'options' => extension_loaded('pdo_mysql') ? array_filter([
                    PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
                ]) : [],
    

    Observ the unix_socket one entry, that is /cloudsql/instance_name and no host, no port, as you connect through the unix socket.