Updated Dec 1, 20266 min read

Create a Cloud SQL Postgres Database Without Terraform

How to create a private Cloud SQL for PostgreSQL instance with gcloud, which network peering, edition, machine size, backup and TLS settings it needs, what the same setup looks like in Terraform, and how to get a Cloud SQL database in your own Google Cloud project from application code.

Illustration for Create a Cloud SQL Postgres Database Without Terraform

Creating a Cloud SQL for PostgreSQL instance is one gcloud command, while a production instance also needs a private IP with a peering connection set up beforehand, an edition that matches the machine size, point-in-time recovery and TLS-only connections.

This guide goes through those steps with gcloud, then Terraform, then a database declared in application code.

What does a Cloud SQL database need?

PieceWhat to decide
Private services accessAn internal range reserved for Google's side of the peering, and a connection to Service Networking
NetworkPrivate IP only, on the VPC your services use
Edition and sizeEnterprise or Enterprise Plus, then a shared-core tier or dedicated CPU and memory
ResilienceRegional availability, daily backups, point-in-time recovery and deletion protection
SecuritySSL mode set to encrypted only, no authorized public networks
Application accessA database, a user for the application and its password delivered as a secret

Private IP requires private services access on the VPC before the instance is created, and the Cloud SQL editions decide which machine types are valid, with Enterprise Plus as the default for new PostgreSQL 16 and later instances.

What are the options besides Terraform?

The console asks the same questions on one long form, and gcloud covers it in a handful of commands. The peering comes first, then the instance, the database and the application user:

~
$ gcloud services enable sqladmin.googleapis.com servicenetworking.googleapis.com$ gcloud compute addresses create sql-range --global --purpose=VPC_PEERING \ --prefix-length=16 --network=main$ gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com \ --ranges=sql-range --network=main$ gcloud sql instances create orders-prod --database-version=POSTGRES_17 \ --edition=enterprise --cpu=2 --memory=8GB --region=europe-west1 \ --network=main --no-assign-ip --ssl-mode=ENCRYPTED_ONLY \ --availability-type=REGIONAL --backup-start-time=03:00 \ --enable-point-in-time-recovery --deletion-protection$ gcloud sql databases create orders --instance=orders-prod$ gcloud sql users create orders_app --instance=orders-prod --password="$APP_DB_PASSWORD"

Every flag is in the gcloud sql instances create reference, and the instance takes several minutes to come up. The application still needs the password in Secret Manager, a way to reach the private IP from Cloud Run through Direct VPC egress or a connector, and a service account with the Cloud SQL Client role if it connects through the Cloud SQL connector. A second environment repeats all of it with new names, which is the repetition Terraform removes.

What does the Terraform look like?

The same database is a reserved range, a Service Networking connection and the instance with its settings, followed by the database itself:

variable "network_id" { type = string } resource "google_compute_global_address" "sql_range" { name = "sql-range" purpose = "VPC_PEERING" address_type = "INTERNAL" prefix_length = 16 network = var.network_id } resource "google_service_networking_connection" "sql" { network = var.network_id service = "servicenetworking.googleapis.com" reserved_peering_ranges = [google_compute_global_address.sql_range.name] } resource "google_sql_database_instance" "orders" { name = "orders-prod" region = "europe-west1" database_version = "POSTGRES_17" deletion_protection = true depends_on = [google_service_networking_connection.sql] settings { edition = "ENTERPRISE" tier = "db-custom-2-8192" availability_type = "REGIONAL" deletion_protection_enabled = true ip_configuration { ipv4_enabled = false private_network = var.network_id ssl_mode = "ENCRYPTED_ONLY" } backup_configuration { enabled = true start_time = "03:00" point_in_time_recovery_enabled = true transaction_log_retention_days = 7 } } } resource "google_sql_database" "orders" { name = "orders" instance = google_sql_database_instance.orders.name }

The arguments are listed in the google_sql_database_instance documentation.

How does Encore create the database from code?

Encore brings infrastructure from code, so a database is declared in the service that uses it, encore run starts Postgres locally, and a deploy to your own Google Cloud project creates the Cloud SQL instance, as the GCP infrastructure docs describe. The instance runs the latest PostgreSQL version on the smallest configuration to begin with, sits in a private network that only your services reach, and keeps daily backups for 7 days with point-in-time recovery.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create orders-app --example=hello-world$ cd orders-app && mkdir -p orders/migrations

The service declares the database next to two endpoints, one that records an order under a client-supplied key so a retried request returns the same row, and one that reads it back:

// orders/orders.go package orders import ( "context" "errors" "encore.dev/beta/errs" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{Migrations: "./migrations"}) type CreateParams struct { Key string `json:"key"` // idempotency key from the client Customer string `json:"customer"` Cents int64 `json:"cents"` } type Order struct { ID int64 `json:"id"` Customer string `json:"customer"` Cents int64 `json:"cents"` } //encore:api public method=POST path=/orders func Create(ctx context.Context, p *CreateParams) (*Order, error) { if p.Key == "" || p.Customer == "" || p.Cents <= 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "key, customer and a positive amount are required"} } o := &Order{} err := db.QueryRow(ctx, ` INSERT INTO orders (idempotency_key, customer, cents) VALUES ($1, $2, $3) ON CONFLICT (idempotency_key) DO NOTHING RETURNING id, customer, cents`, p.Key, p.Customer, p.Cents).Scan(&o.ID, &o.Customer, &o.Cents) if errors.Is(err, sqldb.ErrNoRows) { // The key was used before, so return the order it created. err = db.QueryRow(ctx, ` SELECT id, customer, cents FROM orders WHERE idempotency_key = $1`, p.Key). Scan(&o.ID, &o.Customer, &o.Cents) } if err != nil { return nil, err } return o, nil } //encore:api public method=GET path=/orders/:id func Get(ctx context.Context, id int64) (*Order, error) { o := &Order{ID: id} err := db.QueryRow(ctx, `SELECT customer, cents FROM orders WHERE id = $1`, id).Scan(&o.Customer, &o.Cents) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.NotFound, Message: "order not found"} } if err != nil { return nil, err } return o, nil }
-- orders/migrations/1_create_orders.up.sql CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, idempotency_key TEXT NOT NULL UNIQUE, customer TEXT NOT NULL, cents BIGINT NOT NULL CHECK (cents > 0), created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

encore run applies the migration to a local Postgres and serves both endpoints, and encore db shell orders opens a psql session to look at the rows. The database docs cover migrations and queries, and an instance you already run can be attached instead with Import an existing Cloud SQL instance. To deploy, follow Connect your cloud account for a Google Cloud project and push, and the peering, the instance and the database are created in that project. Encore provisions an IAM role for the service, or a service account on GCP. An AI coding agent that adds a table does it through a numbered migration file in the repository, so the schema change goes through review and the same deploy as the code that uses it.

Best fit: Teams on Google Cloud that want a private, backed-up Cloud SQL Postgres database in their own project, declared next to the service and run locally with encore run.

Frequently asked questions

How do I create a Cloud SQL Postgres instance from the command line?

Reserve an internal range for private services access, connect it to servicenetworking.googleapis.com with gcloud services vpc-peerings connect, then run gcloud sql instances create with a POSTGRES database version, the edition, CPU and memory, --network and --no-assign-ip. Add backups, point-in-time recovery and deletion protection in the same command.

Should a Cloud SQL instance have a public IP?

No. Create it with --no-assign-ip and a private IP on your VPC, set the SSL mode to encrypted only, and reach it from a laptop through the Cloud SQL Auth Proxy or a bastion instead of an authorized network open to the internet.

Why does gcloud reject my tier for a Cloud SQL PostgreSQL instance?

New PostgreSQL 16 and later instances default to the Enterprise Plus edition, which only accepts its own machine types. Pass --edition=enterprise to use shared-core tiers or dedicated cores set with --cpu and --memory.

How do I get a Cloud SQL database without writing the setup by hand?

Declare the database in code with Encore, run encore run to use a local Postgres and deploy to your own Google Cloud project. Encore creates a Cloud SQL for PostgreSQL instance in a private network with daily backups kept for 7 days and point-in-time recovery, and applies your migrations on deploy.

Deploy to your cloud on AWS and Google Cloud without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders