Google Cloud Run: What, Why and How 🚀
Google Cloud Run: What, Why and How
Google Cloud provides many features, and one of them is Google Cloud Run. This article is tailored specifically for beginners seeking to acquire knowledge about Google Cloud Run, providing a comprehensive and accessible guide to facilitate their learning journey. Whenever I embark on learning new topics, I conscientiously consider these three questions — what, why, and how — guiding my efforts to comprehensively understand and address each aspect. In this article, I will endeavor to address these three questions and illustrate concepts through a few examples.
1. What is Google Cloud Run?
When we explore the Google Cloud cheat sheet’s compute section, we will encounter the following options.
Cloud Run is a compute option provided by the Google Cloud Platform, representing a fully managed compute platform. This innovative solution from Google Cloud enables you to seamlessly run containerized applications in a serverless environment.
Here, you might find yourself pondering over two terms. What does “containerized application” signify? And what is the essence of a “serverless environment”?
We will go one by one.
1.1 What does “containerized application” signify?
Containerized applications are applications that run within an isolated package of code called containers. These containers include all the dependencies that an application might need to run on any host operating system, such as libraries, configuration files, and frameworks, amalgamated into a single lightweight executable file.
Here, we are not delving deep into the Docker aspect but will cover the basics.
Docker is a containerization platform used to package applications. It is a tool designed to simplify the creation, deployment, and execution of applications by utilizing containers.
Docker comes into play during the deployment stage.
When you examine the SDLC (Software Development Life Cycle), containerization (Dockerfile) becomes a part of the build phase.
1.2 What is the essence of a “serverless environment”?
Serverless is a cloud-native development model enabling developers to construct and execute applications without the need to oversee servers.
In the context of Cloud Run, it is designed to simplify the deployment and management of applications for developers, alleviating concerns about the underlying infrastructure.
1.3. Key Features
Here are the key features of google cloud run.
Automatically scale
your application in response to incoming requests. → It scale down to zero when there is no traffic → Reducing costs and optimizing resource utilizationPay as you go
pricing model makes it cost effective for various workloads- Can be integrated with continuous integration and
continuous deployment (CI/CD)
pipelines to automate the deployment of containerized applications. - Provides automatic and
built-in load balancing
to distribute incoming requests across multiple instances of your application. Authentication and Authorization
You can use Google Cloud Identity-Aware Proxy (IAP) for authentication and Cloud Identity and Access Management (IAM) for authorization to secure your applications running on Cloud Run.- You can manage configuration and secrets by using environment variables and Google Cloud Secret Manager.
- Cloud Run can be
easily integrated with other Google Cloud services
, such as Cloud Storage, Cloud Firestore, and Cloud Pub/Sub, to build a variety of cloud-native applications.
2. Why do we need cloud run?
Developers are encouraged to explore Google Cloud Run as it heralds a paradigm shift in the deployment and management of applications, presenting an immersive and transformative journey in the realm of development.
- Focus on Innovation, Not Infrastructure: Cloud Run liberates developers from the burdens of managing servers, allowing them to concentrate solely on building robust, scalable applications. By eliminating infrastructure concerns, developers can allocate more time and energy to crafting innovative solutions and enhancing user experiences.
- Streamlined Deployment Process: With Cloud Run, deployment becomes seamless. Developers can swiftly deploy containerized applications without grappling with the complexities of configuring and maintaining servers. This streamlined process enables quicker iterations and faster time-to-market for new features and updates.
- Scalability Without Complexity: The auto-scaling nature of Cloud Run ensures applications can effortlessly handle fluctuating traffic demands. Developers don’t need to worry about scaling configurations; the platform dynamically adjusts resources, ensuring optimal performance without manual intervention.
- Optimized Cost Structure: The pay-as-you-go model of Cloud Run translates into cost efficiency. Developers only pay for the resources consumed during application execution, eliminating the need to provision and pay for idle resources. This cost optimization is especially beneficial for startups and businesses with varying traffic patterns.
- Global Accessibility and Reliability: Google’s infrastructure spans the globe, allowing developers to deploy applications closer to users for reduced latency and improved performance. Additionally, the reliability of Google Cloud ensures high availability, enabling developers to provide consistent services to users across different regions.
- Developer Empowerment and Agility: Cloud Run empowers developers by providing a platform that fosters agility. Its compatibility with container technology allows for flexibility and portability across various environments, ensuring that developers have the freedom to innovate without constraints.
- Future-Ready Infrastructure: By embracing a container-based approach, Cloud Run future-proofs applications. Developers can easily transition and scale applications across different cloud environments or on-premises setups, ensuring flexibility and adaptability as technology landscapes evolve.
However, Cloud Run may not be the best choice for all scenarios. Here are cases where you might want to consider alternative hosting options:
- Stateful Applications: If your application relies on maintaining state on the server, such as in-memory caches, session data, or local file storage, Cloud Run is not suitable. State should be managed externally.
- Long-Running Background Tasks: Cloud Run is designed for short-lived HTTP requests, and it may not be the best choice for running long-running background processes or batch jobs.
- Highly Customized Infrastructure: If your application has very specific infrastructure requirements that cannot be met within Cloud Run’s constraints, you may need a more customizable solution like Google Kubernetes Engine (GKE) or Compute Engine.
- Complex Networking Configurations: For applications requiring complex networking configurations, like VPNs, custom subnets, or custom load balancers, other Google Cloud offerings might be more suitable.
The decision to use Google Cloud Run should be based on your specific application’s requirements, scalability needs, and architectural considerations. It’s essential to evaluate whether Cloud Run aligns with your use case and desired operational model.
3. How to use google cloud run?
Note: It is possible to deploy to Google Cloud Run using containerization. However, if you prefer not to use containerization, you can deploy directly to Google Cloud Run using the gcloud
command. We will see both options in this article.
Below are the steps you need to follow to create and deploy a Google Cloud Run project.
Prerequisites:
- You must have a Google account, create a Google Cloud Project, and enable billing for the project.
- Make sure that the necessary APIs, like the Cloud Run API, are enabled for your project
- If you haven’t already, install the Google Cloud CLI (gcloud) and configure it with your project and preferred region.
Steps:
- Configure containerization for your project.
- Containerize your application using docker
- Push your container image to Artifact Registry.
- From the Google Cloud Run dashboard, select the container image and deploy it to Cloud Run.
Here we are going to see how to deploy a react application to the google cloud run. These are the steps we have to follow to achieve that.
- Create a react project and add Dockerfile and nginx configuration to it.
- Build the react application using the configuration and run it in localhost.
- Once it is working fine in localhost, push the docker image file to artifact registery and deploy it to the cloud run.
Let’s go…
3.1 Create a react project and add Dockerfile and nginx configuration to it.
Here i have added a small react project(using npx create-react-app
) to display the current date and time, and the time will change every second.
Here is the sample code for that.
import { useEffect, useState } from "react";
import "./App.css";
function App() {
let [date, setDate] = useState(new Date());
useEffect(() => {
let timer = setInterval(() => setDate(new Date()), 1000);
return function cleanup() {
clearInterval(timer);
};
});
return (
<div className="App">
<p> Date: {date.toLocaleDateString()} </p>
<h2> Time:{date.toLocaleTimeString()} </h2>
</div>
);
}
export default App;
Once that is done, you have to add the following configuration in your project
- Docker configuration, and
- nginx configuration
Docker configuration
In your project root, create a file with the name Dockerfile
and add the following lines there
FROM node:16.15.1 as build
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
RUN npm run build
FROM nginx:1.19
COPY ./nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 8080
nginx configuration
worker_processes 1;
events {
worker_connections 1024;
}
http {
server {
listen 8080;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
include /etc/nginx/mime.types;
gzip on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
location / {
try_files $uri $uri/ /index.html;
}
}
}
Source code for your reference:
https://github.com/MidhunBalan/gcp_cloud_run_example/tree/main/react-timer
3.2 Build the react application using the configuration and run it in localhost.
Use the following commands to run this project through Docker
To Build The Application
docker build -t app .
To Run Docker App
docker run -p 8080:8080 app
Note: If you are using m1 or m2 or m3 chip, you must use the below command to build it.
docker buildx build --platform linux/amd64 -t app .
Once you succesfully build the docker app, you can open your docker desktop and check whether your app is running or not and simply type localhost:8080 in your browser and see the app running fine in your localhost.
3.3 Push the docker image file to artifact registery and deploy it to the cloud run.
Here we are going to use the gcloud commands. Make sure that you have gcloud installed in your machine.
Step1: Enable google cloud artifactregistry service through gcloud command
gcloud services enable artifactregistry.googleapis.com
Step2: Create artifact repository with a name
gcloud artifacts repositories create {repo-name} --repository-format=docker --location=us-central1 --description="created repo"
Step3: Configure and upload/push the docker image t
gcloud auth configure-docker us-central1-docker.pkg.dev
docker tag {local-image-name} us-central1-docker.pkg.dev/{project-name}/{repo-name}/{gcp-image-name}
docker push us-central1-docker.pkg.dev/{project-name}/{repo-name}/{gcp-image-name}
Once you pushed your changes to artifact registry, you can open the gcloud artifact registry page and simply click on the image and deploy to google cloud run.
Additional Notes:
Is it possible to deploy to the google cloud run without using docker?
Yes. It is possible.
Google has already provided a splendid documentation on this topic. Within the following article, you’ll discover a step-by-step guide on deploying a Node.js application to Google Cloud Run without the need for Docker. https://cloud.google.com/run/docs/quickstarts/build-and-deploy/deploy-nodejs-service
That encapsulates the essence of this topic. Welcome your thoughts and feedback below.