Private Uptime check of Flask API running on Google cloud VM

Ashish Jain
Google Cloud - Community
3 min readJun 6, 2023

Step 1

Start a VM and run a simple flask API on port 8081.

Here it should be on the same VPC network. I will be accessing it using Primary internal IP .

ssh to it , and create a simple app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
return 'It Works!'

Run below commands , mention the port 8081.

export FLASK_ENV=development
export FLASK_APP=api.py
flask run flask run --host=0.0.0.0 --port=8081

It should look like this

Authorize the service account

Uptime checks use a Monitoring-owned service account to manage interactions with the Service Directory service. The service account name has the following format:

gcloud config set project PROJECT_ID
export PROJECT_ID=$(gcloud config get-value core/project)
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='get(projectNumber)')

gcloud projects add-iam-policy-binding $PROJECT_ID \
--member='serviceAccount:@gcp-sa-monitoring-notification.iam.gserviceaccount.com">service-'$PROJECT_NUMBER'@gcp-sa-monitoring-notification.iam.gserviceaccount.com' \
--role='roles/servicedirectory.viewer'

gcloud projects add-iam-policy-binding $PROJECT_ID \
--member='serviceAccount:@gcp-sa-monitoring-notification.iam.gserviceaccount.com">service-'$PROJECT_NUMBER'@gcp-sa-monitoring-notification.iam.gserviceaccount.com' \
--role='roles/servicedirectory.pscAuthorizedService'

Configure firewall : Allow request from below mentioned source-ranges.

Network is default for me , same as vm.

gcloud compute firewall-rules create
--network="default"
--action=allow --direction=ingress --source-ranges="35.199.192.0/19" \
--rules=tcp --project="$PROJECT_ID"

Step 2:

Create a Service directory and mention end points .

Click on Register service and select “Standard” As service type

Mention Region , Namespace ( create if not available ) and unique service name and create it .

Step 3 : Add endpoint in service

After creating the service , add an endpoint in it. Mention the IP address , which is available in step 1 . Here it is Primary Internal IP Address. X.X.0.2

Go to Monitoring and Click on Uptime check . with below configurations

Target -> Protocol : HTTP

Resource Type : Internal IP

Then Select the service directory which is created in step 2.

Leave all other configurations as default . For simplicity I am not adding any notification channel .Test the uptime check by clicking on test, it should give 200 responses if the API is up and running .

You can see the request coming in the ssh window , like below .

After creating the uptime check , you can access the charts like below.

disclaimer : For demo purpose only . Refer Official documentation for detailed guidelines https://cloud.google.com/monitoring/uptime-checks/private-check

--

--