About this codelab
1. Overview
Cloud Run is a fully managed serverless platform that enables you to run stateless containers that are invocable via HTTP requests. This Codelab will demonstrate how to connect a Node.js application on Cloud Run to a Cloud SQL for PostgreSQL database.
What you will learn
In this lab, you will learn how to:
- Create a Cloud SQL for PostgreSQL instance (configured to use Private Service Connect)
- Deploy an application to Cloud Run that connects to your Cloud SQL database
- Use Gemini Code Assist to add functionality to your application
What you will learn
- Create a Cloud SQL for PostgreSQL instance (configured to use Private Service Connect)
- Deploy an application to Cloud Run that connects to your Cloud SQL database
- Use Gemini Code Assist to add functionality to your application
2. Prerequisites
- If you do not already have a Google account, you must create a Google account.
- Use a personal account instead of a work or school account. Work and school accounts may have restrictions that prevent you from enabling the APIs needed for this lab.
3. Project setup
- Sign-in to the Google Cloud Console.
- Enable billing in the Cloud Console.
- Completing this lab should cost less than $1 USD in Cloud resources.
- You can follow the steps at the end of this lab to delete resources to avoid further charges.
- New users are eligible for the $300 USD Free Trial.
- Create a new project or choose to reuse an existing project.
4. Open Cloud Shell Editor
- Navigate to Cloud Shell Editor
- If the terminal doesn't appear on the bottom of the screen, open it:
- Click the hamburger menu
- Click Terminal
- Click New Terminal
- Click the hamburger menu
- In the terminal, set your project with this command:
- Format:
gcloud config set project [PROJECT_ID]
- Example:
gcloud config set project lab-project-id-example
- If you can't remember your project id:
- You can list all your project ids with:
gcloud projects list | awk '/PROJECT_ID/{print $2}'
- You can list all your project ids with:
- Format:
- If prompted to authorize, click Authorize to continue.
- You should see this message:
If you see aUpdated property [core/project].
WARNING
and are askedDo you want to continue (Y/N)?
, then you have likely entered the project ID incorrectly. PressN
, pressEnter
, and try to run thegcloud config set project
command again.
5. Enable APIs
In the terminal, enable the APIs:
gcloud services enable \
compute.googleapis.com \
sqladmin.googleapis.com \
run.googleapis.com \
artifactregistry.googleapis.com \
cloudbuild.googleapis.com \
networkconnectivity.googleapis.com \
servicenetworking.googleapis.com \
cloudaicompanion.googleapis.com
If prompted to authorize, click Authorize to continue.
This command may take a few minutes to complete, but it should eventually produce a successful message similar to this one:
Operation "operations/acf.p2-73d90d00-47ee-447a-b600" finished successfully.
6. Set up a Service Account
Create and configure a Google Cloud service account to be used by Cloud Run so that it has the correct permissions to connect to Cloud SQL.
- Run the
gcloud iam service-accounts create
command as follows to create a new service account:gcloud iam service-accounts create quickstart-service-account \
--display-name="Quickstart Service Account" - Run the gcloud projects add-iam-policy-binding command as follows to add the Log Writer role to the Google Cloud service account you just created.
gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
--member="serviceAccount:quickstart-service-account@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
--role="roles/logging.logWriter"
7. Create Cloud SQL Instance
- Create a Service Connection Policy to allow network connectivity from Cloud Run to Cloud SQL with Private Service Connect
gcloud network-connectivity service-connection-policies create quickstart-policy \
--network=default \
--project=${GOOGLE_CLOUD_PROJECT} \
--region=us-central1 \
--service-class=google-cloud-sql \
--subnets=https://www.googleapis.com/compute/v1/projects/${GOOGLE_CLOUD_PROJECT}/regions/us-central1/subnetworks/default - Generate a unique password for your database
export DB_PASSWORD=$(openssl rand -base64 20)
- Run the
gcloud sql instances create
command to create a Cloud SQL instancegcloud sql instances create quickstart-instance \
--project=${GOOGLE_CLOUD_PROJECT} \
--root-password=${DB_PASSWORD} \
--database-version=POSTGRES_17 \
--tier=db-perf-optimized-N-2 \
--region=us-central1 \
--ssl-mode=ENCRYPTED_ONLY \
--no-assign-ip \
--enable-private-service-connect \
--psc-auto-connections=network=projects/${GOOGLE_CLOUD_PROJECT}/global/networks/default
This command may take a few minutes to complete.
- Run the
gcloud sql databases create
command to create a Cloud SQL database within thequickstart-instance
.gcloud sql databases create quickstart_db \
--instance=quickstart-instance
8. Prepare Application
Prepare a Node.js application that responds to HTTP requests.
- In Cloud Shell create a new directory named
helloworld
, then change into that directory:mkdir helloworld
cd helloworld - Initialize a
package.json
file as a module.npm init -y
npm pkg set type="module"
npm pkg set main="index.mjs"
npm pkg set scripts.start="node index.mjs" - Install
pg
to interact with the PostgreSQL database.npm install pg
- Install express to accept incoming http requests.
npm install express
- Create an
index.mjs
file with the application code. This code is able to:- Accept HTTP requests
- Connect to the database
- Store the time of the HTTP request in the database
- Return the times of the last five requests
cat > index.mjs << "EOF"
import express from 'express';
import pg from 'pg';
const { Pool } = pg;
const pool = new Pool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
ssl: {
require: true,
rejectUnauthorized: false, // required for self-signed certs
// https://node-postgres.com/features/ssl#self-signed-cert
}
});
const app = express();
app.get('/', async (req, res) => {
await pool.query('INSERT INTO visits(created_at) VALUES(NOW())');
const {rows} = await pool.query('SELECT created_at FROM visits ORDER BY created_at DESC LIMIT 5');
console.table(rows); // prints the last 5 visits
res.send(rows);
});
const port = parseInt(process.env.PORT) || 8080;
app.listen(port, async () => {
console.log('process.env: ', process.env);
await pool.query(`CREATE TABLE IF NOT EXISTS visits (
id SERIAL NOT NULL,
created_at timestamp NOT NULL,
PRIMARY KEY (id)
);`);
console.log(`helloworld: listening on port ${port}`);
});
EOF
This code creates a basic web server that listens on the port defined by the PORT environment variable. The application is now ready to be deployed.
9. Deploy the application to Cloud Run
- Run the gcloud projects add-iam-policy-binding command as follows to add the Network User role to the Cloud Run service account for the Cloud Run service you are about to create.
gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
--member "serviceAccount:service-$(gcloud projects describe ${GOOGLE_CLOUD_PROJECT} --format="value(projectNumber)")@serverless-robot-prod.iam.gserviceaccount.com" \
--role "roles/compute.networkUser"
- Run the command below to deploy your application to Cloud Run:
gcloud run deploy helloworld \
--region=us-central1 \
--source=. \
--set-env-vars DB_NAME="quickstart_db" \
--set-env-vars DB_USER="postgres" \
--set-env-vars DB_PASSWORD=${DB_PASSWORD} \
--set-env-vars DB_HOST="$(gcloud sql instances describe quickstart-instance --project=${GOOGLE_CLOUD_PROJECT} --format='value(settings.ipConfiguration.pscConfig.pscAutoConnections.ipAddress)')" \
--service-account="quickstart-service-account@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
--network=default \
--subnet=default \
--allow-unauthenticated - If prompted, press
Y
andEnter
to confirm that you would like to continue:Do you want to continue (Y/n)? Y
After a few minutes, the application should provide a URL for you to visit.
Navigate to the URL to see your application in action. Every time you visit the URL or refresh the page, you will see the five most recent visits returned as JSON.
10. Congratulations
In this lab, you have learned how to do the following:
- Create a Cloud SQL for PostgreSQL instance (configured to use Private Service Connect)
- Deploy an application to Cloud Run that connects to your Cloud SQL database
- Use Gemini Code Assist to add functionality to your application
Clean up
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources. If you would like to delete the entire project, you can run:
gcloud projects delete ${GOOGLE_CLOUD_PROJECT}