Google Cloud Run

                                       Google Cloud Run


Google Cloud Run is a managed compute platform. 

Allows running of front-end and back-end services, batch jobs and websites.

Cloud run is based on containers. You need to package your code and the dependencies for that code in a Docker container.

You first need to create a container image of your app.

Next you need to push the image to the Artifact Registry which stores and  manages these images.

A URL is built allowing the users to run the code.

No infrastructure is needed. Cloud run provides that.

Only pay when traffic occurs, not when idle.

Can run concurrently meaning can handle many requests at the same time.

It supports automatic scaling which will provide computing resources as traffic occurs.

It simplifies running workloads and provides fully managed compute to run containers that can scale up and down depending on traffic.

Also, secure endpoints are delivered using TLS.

API’s

Google Cloud APIs & Services allow cloud developers to access Google's  infrastructure.

Service is a product you will need to build various types of projects.

API (Application Programming Interface) allows you to access key functionality needed for those projects. In order to use key Google functionality the developer must enable the specific API needed for the projects.


Note: You may need to turn on 2FA

Go to settings

Then Turn on 2-Step Verification

Then click Done


For Cloud run we need to enable the  Cloud Run Admin API 

To do this we need to search for APIs & Services


And click the APIs & Services link

Then click Enable APIs and services link



Search for Cloud Run Admin API


Click Enable


Next we need to enable the Artifact Registry API

This is needed to store container images

Then enable Cloud Build API which lets Google build code into a Container.

Then enable Compute Engine API allows access to virtual machines


This step also creates a service account 


Basic Cloud run process



Type cloud run in the search bar at top of screen and select Cloud Run


Click on Deploy container


Click Deploy one revision from an existing container image


Click Test with a sample container

It brings up a test container

In the Region dialog box pick us-east1(South Carolina)

Click on Allow public access

Click Create

Click into the URL

Hello World Cloud run 


We need to grant permission for our service account to properly create a cloud run process.

Service Account allows services to access resources on your behalf.

It functions as an "Identity" to perform certain actions on the project.

In the case of cloud run it needs Artifact Registry Writer permissions to upload files as well as permission to store files in the Docker repository for container images.

We will need to grant the service account roles to perform these functions.

A Google Cloud service account is a special type of Google account intended to represent a non-human entity—such as an application, virtual machine (VM), container, or automated script—rather than an individual user.

They act as a secure bridge, allowing your software systems to authenticate and securely interact with Google Cloud APIs and services (like Cloud Storage, BigQuery, or Cloud SQL) without requiring human intervention or embedding personal user credentials.

Key Characteristics & Functions

Acts as an Identity and a Resource: A service account has its own unique email address (e.g., my-service-account@project-id.iam.gserviceaccount.com). In Google Cloud IAM (Identity and Access Management), you can treat it as an identity by granting it specific roles, or treat it as a resource whose access you want to control.

Machine-to-Machine Authentication: Instead of passwords, service accounts rely on cryptographic keys or short-lived OAuth 2.0 access tokens.

Principle of Least Privilege: Because they can be tightly scoped, you can grant a service account access only to the exact resources it needs (e.g., read-only access to a single Cloud Storage bucket), avoiding the security risks of broad or human-level administrative permissions.

Common Use Cases

Running Workloads on Compute Resources: Attaching a service account to a Compute Engine virtual machine, Cloud Run service, or Cloud Function allows the code running inside it to inherit those permissions automatically.

CI/CD Pipelines & Automation: Automated deployment scripts, GitHub Actions, or Jenkins servers use service accounts to authenticate securely when pushing container images to Artifact Registry or deploying updates.

Cross-Service Communication: Allowing a backend application (like a Flask or Node.js server) to securely query a database or read/write files to cloud storage.

Types of Service Accounts

User-Managed Service Accounts: Created and managed explicitly by you. You control their lifecycle, keys, and IAM roles. These are ideal for custom applications and production workloads.

Google-Managed Service Accounts: Automatically created by Google Cloud when you enable certain APIs or services (such as the Compute Engine default service account) to execute internal processes on your behalf.



Service accounts do not need passwords and allow for platform 

communication without human intervention.

First, we need to see the full name of the service account of the project.


Go to the cloud shell.


Welcome to Cloud Shell! Type "help" to get started, or type "gemini" to try prompting with Gemini CLI.

Your Cloud Platform project in this session is set to project-19ed9eac-5674-4138-9fc.

Use `gcloud config set project [PROJECT_ID]` to change to a different project.


Need to obtain the name of the service account for this project by using the gcloud command


$ gcloud iam service-accounts list

DISPLAY NAME: Default compute service account

EMAIL: 344965500335-compute@developer.gserviceaccount.com

DISABLED: False

bg4stamford@cloudshell:~ (project-19ed9eac-5674-4138-9fc)$ 



Get the project id from the project window in the google cloud console.

Click on Project name



Copy ID project-19ed9eac-5674-4138-9fc


Now execute the console command 

gcloud iam service-accounts list


$ gcloud iam service-accounts list

DISPLAY NAME: Default compute service account

EMAIL: 344965500335-compute@developer.gserviceaccount.com

DISABLED: False



You need to add the role of artifactregistry.writer to the service account created for that project. 



gcloud projects add-iam-policy-binding PROJECT-ID --member=”serviceAccount:SERVICE-ACCOUNT-NAME”  --role="roles/artifactregistry.writer"


Now execute the command 


$ gcloud projects add-iam-policy-binding project-19ed9eac-5674-4138-9fc --member="serviceAccount:344965500335-compute@developer.gserviceaccount.com" --role="roles/artifactregistry.writer"

Updated IAM policy for project [project-19ed9eac-5674-4138-9fc].

bindings:


Next we need to create a repository to store the docker container.


Syntax is


 gcloud artifacts repositories create cloud-run-source-deploy --repository-format=docker --location=REGION --project=PROJECT-ID



$ gcloud artifacts repositories create cloud-run-source-deploy --repository-format=docker --location=us-central1 --project=project-19ed9eac-5674-4138-9fc


Create request issued for: [cloud-run-source-deploy]

bg4stamford@cloudshell:~ (project-19ed9eac-5674-4138-9fc)$ 



Lastly, we need to provide a role for the service account to view storage


Syntax is


gcloud projects add-iam-policy-binding PROJECT-ID  --member="serviceAccount:SERVICE-ACCOUNT-NAME" --role="roles/storage.objectViewer"


$ gcloud projects add-iam-policy-binding project-19ed9eac-5674-4138-9fc --member="serviceAccount:344965500335-compute@developer.gserviceaccount.com" --role="roles/storage.objectViewer"

Updated IAM policy for project [project-19ed9eac-5674-4138-9fc].


Create a directory for your hello world application

john_iacovacci1@cloudshell:~ (cloud-project-examples)$ mkdir hellocloud

john_iacovacci1@cloudshell:~ (cloud-project-examples)$ cd hellocloud

john_iacovacci1@cloudshell:~/hellocloud (cloud-project-examples)$ 

Create a main.py file in that directory

====================================================

import os

from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello_world():

   return f"Hello Google World!"

if __name__ == "__main__":

    port = int(os.environ.get("PORT", 8080))

    app.run(debug=True, host="0.0.0.0", port=port)

====================================================

Next we need to create a requirements.txt file for the application

====================================================

Flask==3.0.0

gunicorn==21.2.0

====================================================

We are now ready to deploy this application


$ gcloud run deploy python-hello-world --source . --allow-unauthenticated --region us-central1

Deploying from source requires an Artifact Registry Docker repository to store built containers. A repository named [cloud-run-source-deploy] in region 

[us-central1] will be created.


Do you want to continue (Y/n)?  Y


Building using Buildpacks and deploying container to Cloud Run service [python-hello-world] in project [cloud-project-examples] region [us-central1]

Building and deploying...                                                                                                      

  Validating Service...done                                                                                                    

  Uploading sources...done                                                                                                     

  Building Container... Logs are available at [https://console.cloud.google.com/cloud-build/builds;region=us-central1/191656d0-

  738d-4248-a4f3-726747439ba0?project=517129368909]....done                                                                    

  Setting IAM Policy...done                                                                                                    

  Creating Revision...done                                                                                                     

  Routing traffic...done                                                                                                       

Done.                                                                                                                          

Service [python-hello-world] revision [python-hello-world-00004-466] has been deployed and is serving 100 percent of traffic.

Service URL: https://python-hello-world-517129368909.us-central1.run.app

john_iacovacci1@cloudshell:~/hellocloud (cloud-project-examples)$ 

Click on link brings message up in browser



Cloud Run Hello World Explained

Flask

Flask is a micro web framework written in Python.


A Backend framework plays a crucial role in building robust and efficient web applications. 


 It is a lightweight WSGI web application. 


Framework designed to get started quickly and scale applications.


A web framework is designed to support the development of web applications.



import os


The import os library allows for the python program to interact with the Operating System


from flask import Flask

This pulls in the Flask class for use.


app = Flask(__name__)

Creates an "instance" of the Flask.

 The __name__ argument helps determine the root path of the application.

__name__ is a built-in variable that evaluates name of the current module. 


@app.route("/")

the route() decorator to bind a function to a URL.

Routing is mapping the URL directly to the code.

When a user clicks the URL it triggers the function.


def hello_world():

   return f"Hello Google World!"


Function that runs and returns the string "Hello Google World!" in your browser.

if __name__ == "__main__":

'__main__' is the name of the scope in which top-level code executes. Ensures the server will start. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.


port = int(os.environ.get("PORT", 8080))

Sets the communication port to use and checks the operating system for port availability.


app.run(debug=True, host="0.0.0.0", port=port)

Launch the local server. Enables debug mode. Tells the server to listen to all available network interfaces.

App - The core web application object.

@app.route - Maps a URL path to a Python function.

App.run - Starts the actual web server.

Os.environ - Fetches configuration from the system environment.

App.run - Starts the actual web server.


The main.py program


====================================================

import os

from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello_world():

   return f"Hello Google World!"

if __name__ == "__main__":

    port = int(os.environ.get("PORT", 8080))

    app.run(debug=True, host="0.0.0.0", port=port)

==============================================


requirements.txt file is used for specifying what python packages are required to run the project you are looking at. 

Flask==3.0.0

gunicorn==21.2.0

Gunicorn (Green Unicorn) translates requests from the internet so your Python web application can understand.

 The requirements.txt file

============================================

Flask==3.0.0


gunicorn==21.2.0

===========================================

$ gcloud run deploy python-hello-world --source . --allow-unauthenticated --region us-central1


Instructs Cloud run to build a container using the python code and host it on the web.

gcloud run deploy - create a service on Cloud Run.

Python-hello-world - Name of your service, part of URL.

--source - Tells process to look at the current directory (.

--allow-unauthenticated - Allows all users to access service. 

--region us-central1 - This makes your service public. 


Command will:

Build the Image: Package your Python code into a Docker container.

Stores the Image: saves that package in the Artifact Registry.

Deploys: starts an instance of that container.

Provides a URL: Gives you a generated HTTPS link.


 

Docker Containers


Containers allow the developer to package an environment for applications


The advantages are to have applications run uniformly and consistently on various machine configurations.

Standardization 

Create independent and isolated user-space instances that can be managed in tandem.

Lightweight virtual machines environments that are Inexpensive to run

Docker containerization provides speed, efficiency, and scalability for application deployment.

Containers share the host's Linux kernel.


Install - Configure - Deploy -Maintain

The Dockerfile defines the container image for the application to run on. 

It tells the application how to build the image environment, libraries, operating system, code and works anywhere that Docker is installed on a Linux machine.


The example below defines a docker app for “Hello World”.


Go to Linux shell and create director called hellodocker and cd into it


john_iacovacci1@cloudshell:~ (cloud-project-examples)$ mkdir hellodocker

john_iacovacci1@cloudshell:~ (cloud-project-examples)$ cd hellodocker

john_iacovacci1@cloudshell:~/hellodocker (cloud-project-examples)$ 



joh


It starts with the app.py python file.


Open editor to create file


======================================================

# app.py

from flask import Flask

import os


app = Flask(__name__)


@app.route("/")

def hello_world():

    return "Hello, Google Cloud Users!."


if __name__ == "__main__":

   

# Cloud Run listens on the port defined by the PORT environment variable

    port = int(os.environ.get("PORT", 8080))

    app.run(debug=True, host='0.0.0.0', port=port)


========================================================


The application “Listens” to activity on a specific PORT and executes the function hello_world() when the application link is clicked.



The Dockerfile is needed which will provide the instructions for the application to run on.


========================================================# #Use the official lightweight Python image

FROM python:3.11-slim


# Set the working directory in the container

WORKDIR /app


# Copy the local code to the container

COPY . .


# Install Flask

RUN pip install Flask


# Run the web service on container startup

CMD ["python", "app.py"]

========================================================



Next we need to permission our account


To enable services, account needs the Service Usage Admin role roles/serviceusage.serviceUsageAdmin

The broader Editor/Owner role.

Check IAM & Admin > IAM

roles/serviceusage.serviceUsageAdmin

roles/resourcemanager.projectIamAdmin 



john_iacovacci1@cloudshell:~/hellodocker (cloud-project-examples)$ gcloud run deploy hello-python --source . --region us-central1 --allow-unauthenticated

Building using Dockerfile and deploying container to Cloud Run service [hello-python] in project [cloud-project-examples] region [us-central1]

Building and deploying...                                                                                                      

  Validating Service...done                                                                                                    

  Uploading sources...done                                                                                                     

  Building Container... Logs are available at [https://console.cloud.google.com/cloud-build/builds;region=us-central1/d9b9a54c-

  39c9-471c-84c5-87c7fba3cd84?project=517129368909]....done                                                                    

  Setting IAM Policy...done                                                                                                    

  Creating Revision...done                                                                                                     

  Routing traffic...done                                                                                                       

Done.                                                                                                                          

Service [hello-python] revision [hello-python-00003-hgh] has been deployed and is serving 100 percent of traffic.

Service URL: https://hello-python-517129368909.us-central1.run.app


Click on the service URL link


john_iacovacci1@cloudshell:~/hellodocker (cloud-project-examples)$ 




No comments:

Post a Comment

Fairfield County

Fairfield County The overall yearly financial dollar value generated in Fairfield County, measured by its Gross Domestic Product (GDP) , is ...