#
Connect to a PostgreSQL database from GCP CLI
This tutorial explains how we can connect to a PostgreSQL database from GCP CLI.
Info
This tutorial is based on Create a PostgreSQL database.
Info
Cloud Shell doesn't work with a private IP address. These instructions are only for an instance with a public IP address.
Info
Prerequisite: To have the PostgreSQL client installed on our machine.
The first step is to open the Command Prompt and run the following command in order to login to our GCP account.
gcloud auth login
Now we can use the gcloud sql connect
command in order to connect to our PostgreSQL instance.
gcloud sql connect postgres1db --user=postgres
Info
Is it possible to receive the following message "API [sqladmin.googleapis.com] not enabled on project [476731510945]. Would you like to enable and retry (this will take a few minutes)? (y/N)?". Click on y.
In the console you will see something like this:
Allowlisting your IP for incoming connection for 5 minutes...done.
Connecting to database with SQL user [postgres].Password:
psql (14.6, server 14.4)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.
You can test your connection by running the \l
command:
postgres=> \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
---------------+-------------------+----------+------------+------------+-----------------------------------------
cloudsqladmin | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 |
postgres | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 |
template0 | cloudsqladmin | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqladmin +
| | | | | cloudsqladmin=CTc/cloudsqladmin
template1 | cloudsqlsuperuser | UTF8 | en_US.UTF8 | en_US.UTF8 | =c/cloudsqlsuperuser +
| | | | | cloudsqlsuperuser=CTc/cloudsqlsuperuser
(4 rows)