0
0
GcpHow-ToBeginner · 3 min read

How to Use Private IP for Cloud SQL in GCP

To use a private IP for Cloud SQL, enable the private IP option when creating or configuring your Cloud SQL instance and connect from resources within the same VPC network. This ensures your database traffic stays inside your private network without using public internet.
📐

Syntax

When creating a Cloud SQL instance with private IP, you specify the privateNetwork field to link the instance to a VPC network. This allows the instance to have an internal IP address accessible only within that network.

Key parts:

  • name: The instance name.
  • databaseVersion: The SQL engine version.
  • settings: Configuration settings like tier and storage.
  • ipConfiguration.privateNetwork: The full resource name of the VPC network for private IP.
json
{
  "name": "my-instance",
  "databaseVersion": "POSTGRES_14",
  "settings": {
    "tier": "db-f1-micro"
  },
  "ipConfiguration": {
    "privateNetwork": "projects/my-project/global/networks/my-vpc-network"
  }
}
💻

Example

This example shows how to create a Cloud SQL PostgreSQL instance with private IP enabled using gcloud CLI. It demonstrates specifying the VPC network and connecting securely within the network.

bash
gcloud sql instances create my-private-instance \
  --database-version=POSTGRES_14 \
  --tier=db-f1-micro \
  --network=projects/my-project/global/networks/my-vpc-network \
  --no-assign-ip
Output
Created [https://sqladmin.googleapis.com/sql/v1beta4/projects/my-project/instances/my-private-instance].
⚠️

Common Pitfalls

  • Not enabling private services access in your VPC network before creating the instance causes private IP setup to fail.
  • Trying to connect from outside the VPC network will not work because private IP is only accessible internally.
  • Forgetting to disable public IP or assigning a public IP can expose your database to the internet unintentionally.
bash
Wrong way:
gcloud sql instances create my-instance \
  --database-version=POSTGRES_14 \
  --tier=db-f1-micro

Right way:
gcloud sql instances create my-instance \
  --database-version=POSTGRES_14 \
  --tier=db-f1-micro \
  --network=projects/my-project/global/networks/my-vpc-network \
  --no-assign-ip
📊

Quick Reference

StepDescription
Enable Private Services AccessReserve IP range and enable private services in your VPC.
Create Cloud SQL with private IPUse --network flag and disable public IP.
Connect from same VPCUse the private IP address from your VM or service.
Verify connectivityTest connection using psql or client tools inside VPC.

Key Takeaways

Enable private services access and reserve IP range before using private IP.
Create Cloud SQL instance with the --network flag to assign private IP.
Connect only from resources inside the same VPC network.
Disable public IP to keep your database secure and private.
Use gcloud CLI or Cloud Console to configure private IP easily.