Hubert Cumberdale
Hubert Cumberdale

Reputation: 1

"Can't reach database server" Trying to connect Google Cloud SQL to PostgreSQL Prisma Database

I'm trying to use a PostgreSQL database with Prisma for the first time in my project. However, I'm failing to connect to the Cloud SQL instance I created on Google Cloud. When I run npx prisma db push, I'm getting the error:

Please make sure your database server is running at `34.86.23.139`:`5432`.
 ERROR  Command failed with exit code 1: prisma db push

I made sure the database server was running, and was able to successfully connect to it using Cloud Shell. The public IP address of the server is 34.86.23.139, the name of the database is test-db, and the connection name is test:us-east4:test-db. Given that the connection string should be in the formal of postgresql://USER:PASSWORD@HOST:PORT/DATABASE, I made this within .env:

//.env

DATABASE_URL="postgresql://[email protected]:[email protected]/test-db"
// I also tried DATABASE_URL="postgresql://[email protected]:[email protected]/test:us-east4:test-db" but same error.

And this is my schema.prisma:

// prisma/schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Thing {
  id Int @id @default(autoincrement())
  name String
}

Please let me know what I'm doing wrong. I'm a newbie so go easy on me :) Thank you in advance.

Upvotes: 0

Views: 1691

Answers (2)

Joan Fabrégat
Joan Fabrégat

Reputation: 131

If you use the CloudSQL Auth Proxy (corresponding to the "Cloud SQL connections" option of your Cloud Run service's configuration), the connection has to go through a Unix socket. The socket is automatically available in the service container at the path /cloudsql/*connection-name* where connection-name is the connection name of the Cloud SQL instance (ex: project-id:region:instance-name, available on the overview tab). See this quick start guide for more informations.

According to PrismaDB documentation, you need to change the value of the DATABASE_URL env var to include the path to the Unix socket (the host has to be localhost in this case):
mysql://*user*:*pwd*@localhost/*database*?socket=/cloudsql/*project-id:region:instance-name*

Hope it helps!

Upvotes: 0

enocom
enocom

Reputation: 1816

Cloud SQL instances are configured to block all traffic to the public IP unless you specifically allow an IP using Authorized Networks.

Alternatively, you can run the Cloud SQL Auth Proxy next to your application and it will create a listener on localhost that proxies traffic to your instance without having to configure Authorized Networks.

Upvotes: 1

Related Questions