An Overview of Google Cloud Run

Serverless computing is a buzz word and used by many organizations to get rid of management of infrastructure and for automatic scaling of business applications. Usage of such technology in computing environments help organizations to focus on core business implementations such as building applications, software and others while management aspects are taken care by the cloud service provider. Infrastructure management tasks automation help in running stateless containers in a fully managed environment.

In today’s topic we will learn about Google Cloud Run, its key features, use cases, how to deploy Google cloud run and how it works. 

What is Google Cloud Run

Google cloud run is a managed computing platform to run containers which are invoked with requests and events. It operates on a serverless container architecture. Due to its serverless architecture all infrastructure management tasks are abstracted so that users can focus on building good applications.

Cloud run takes up a container with a pre-built application to deploy it on a serverless environment and eliminates the requirement of managing the resources or infrastructure creation for the IT team. The logic embedded within containers should be stateless, and one should specify the combination of CPU vs memory resources along with all concurrencies. A persistent volume needs to be attached to the container when it is running to prevent deletion of any data stored within the container. 

There are specific requirements for containers which need to be added to cloud run as under:

  • 64-bit Linux compiled containers
  • Ability to listen all HTTP requests over port 8080
  • Ability to fit within a memory scale of 2GB.
  • All container instances start from an HTTP server within the next 4 minutes of receiving a request.
  • The applications need to be container ready 

Features of Cloud Run

  • Users can use any programming languages to build their applications 
  • There is no infrastructure management required to deploy application and cloud run will manage all services for you
  • It automatically scales up and down applications based on network traffic
  • It is built on an open source project named Knative to enable workload portability across platforms
  • It maps services to domain of users
  • It provides a simple command line interface to help in quick deployment and management of services
  • It runs its services globally and auto replicates across multiple zones

Use Cases for Google Cloud Run

  • Webservices – Backoffice administration requires documentation, spreadsheets or vendor supplied web applications. Hosting containerized internal web applications on cloud run is suited for always ready to use and billed only when in use.
  • Data processing applications can be built using google cloud run to extract, structured data and store in Big Query tables.
  • Website web services can be build using mature technologies such as nginx, ExpressJS, Django to render dynamic HTMPL pages
  • REST API backend hosted on Google cloud run allows developers to persist data reliability for managed databases. 
  • Automation for scheduled document generation – using this feature jobs can be scheduled such as invoice generation and will be billed on when invoice is generated.

How to deploy Google Cloud Run?

To use google cloud run you need to have a google account

Step 1: Go to google cloud console and login with registered ID

Step 2: In console click on navigation menu and click on cloud run

Step 3: Click on create a service

Step 4: The cloud run will be enabled automatically when create a service option is clicked

Step 5: In create service provide following details and click on next to continue

Service name: K21-cloudrun-service
Deployment platform: cloud run

Region: us-central1 (choose region closed to your location)

Step 6: in configure service first revision enter following details and click next
Choose deploy one revision from existing container image
For the container image use us-docker.pkg.dev/cloudrun/container/hello

Step 7: Now configure how this service will be triggered from Choose option Allow all traffic and Allow unauthenticated invocations in the respective fields. Click on Create to deploy the image to Cloud Run and let deployment finish.

Step 8: Deployment will be completed in sometime

Step 9: To verify deployment status copy URL generated in cloud run details page

Step 10: Copy URL in browser and you will see successfully deployed container image on cloud run

How Google Cloud Run works

Cloud Run service can be triggered/invoked by:

1. HTTP Requests

You can directly make HTTP requests to your Cloud Run service.

Example using curl:

curl -X POST https://YOUR_CLOUD_RUN_SERVICE_URL -H "Authorization: Bearer $(gcloud auth print-identity-token)" -H "Content-Type: application/json" -d '{"key":"value"}'

Example using Python with requests:

import requests

from google.auth import default

from google.auth.transport.requests import Request

# Get default credentials and project ID

credentials, project = default()

# Get an identity token for the Cloud Run service

auth_req = Request()

credentials.refresh(auth_req)

token = credentials.id_token

# Cloud Run service URL

service_url = "https://YOUR_CLOUD_RUN_SERVICE_URL"

# Make a request to the service

response = requests.post(

    service_url,

    headers={"Authorization": f"Bearer {token}"},

    json={"key": "value"}

)

print(response.json())

2. gRPC

Cloud Run supports gRPC, a high-performance RPC framework.

Example using gRPC in Python:

Define your service in a .proto file.

Generate the gRPC client and server code using protoc.

Implement the server and deploy it to Cloud Run.

Write a gRPC client to invoke the service.

3. Pub/Sub

Google Cloud Pub/Sub can trigger Cloud Run services asynchronously.

Create a Pub/Sub topic:

gcloud pubsub topics create YOUR_TOPIC

Deploy your Cloud Run service with Pub/Sub trigger:

gcloud run deploy --image gcr.io/YOUR_PROJECT/YOUR_IMAGE --platform managed --trigger-topic YOUR_TOPIC

Publish a message to the topic:

from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()

topic_path = publisher.topic_path('YOUR_PROJECT', 'YOUR_TOPIC')

data = 'Hello, World!'

publisher.publish(topic_path, data.encode('utf-8'))

4. Cloud Scheduler

Cloud Scheduler can be used to schedule HTTP calls to your Cloud Run service.

Create a Cloud Scheduler job:

gcloud scheduler jobs create http YOUR_JOB_NAME --schedule "*/5 * * * *" --uri "https://YOUR_CLOUD_RUN_SERVICE_URL" --http-method POST --oidc-service-account-email "YOUR_SERVICE_ACCOUNT"

5. Web Sockets

Cloud Run currently does not support WebSockets directly. You would need to use a proxy like Cloud Run for Anthos or use another service like Firebase Realtime Database or Firestore for real-time capabilities.

6. Cloud Tasks

Google Cloud Tasks can be used to enqueue HTTP tasks to your Cloud Run service.

Create a task queue:

gcloud tasks queues create YOUR_QUEUE

Create a task:

from google.cloud import tasks_v2

from google.protobuf import timestamp_pb2

import datetime

client = tasks_v2.CloudTasksClient()

project = 'YOUR_PROJECT'

queue = 'YOUR_QUEUE'

location = 'YOUR_LOCATION'

url = 'https://YOUR_CLOUD_RUN_SERVICE_URL'

payload = 'Hello, World!'

parent = client.queue_path(project, location, queue)

task = {

    'http_request': { 

        'http_method': tasks_v2.HttpMethod.POST,

        'url': url,

        'headers': {

            'Content-Type': 'application/json'

        },

        'body': payload.encode()

    }

}

response = client.create_task(parent, task)

print('Created task {}'.format(response.name))

7. Firebase

Firebase can be used in conjunction with Cloud Run for various use cases.

Example using Firebase Functions to invoke Cloud Run:

const functions = require('firebase-functions');

const fetch = require('node-fetch');

exports.invokeCloudRun = functions.https.onRequest(async (req, res) => {

    const response = await fetch('https://YOUR_CLOUD_RUN_SERVICE_URL', {

        method: 'POST',

        headers: {

            'Authorization': `Bearer ${await getAccessToken()}`,

            'Content-Type': 'application/json'

        },

        body: JSON.stringify({ key: 'value' })

    });

    const data = await response.json();

    res.send(data);

});

async function getAccessToken() {

    const { GoogleAuth } = require('google-auth-library');

    const auth = new GoogleAuth({

        scopes: 'https://www.googleapis.com/auth/cloud-platform'

    });

    const client = await auth.getClient();

    const token = await client.getAccessToken();

    return token;

}

These methods cover a wide range of scenarios for invoking a Cloud Run service. Each method has its own use cases and can be chosen based on the requirements of your application.

Leave a Comment

Select your currency
INR Indian rupee