Blogs
Developing Applications on Google Cloud empowers developers to leverage a comprehensive suite of cloud services for building, deploying, and scaling applications with ease. With tools like Cloud Functions for event-driven code execution, Cloud Datastore for scalable NoSQL databases, Cloud Storage for robust object storage, Cloud Run for containerized application deployment, and Cloud Build for automated CI/CD pipelines, developers can create innovative solutions while focusing on their core business logic. Google Cloud's managed services abstract away infrastructure complexities, enabling developers to accelerate development cycles and deliver high-performing applications to users worldwide.
In Google Cloud Platform (GCP), users can create and manage services using two interfaces:
GCP Console (Graphical Interface):
gcloud CLI (Command-Line Interface):
To initiate your journey with Google Cloud services, you must first create a project within the Google Cloud Console and subsequently access services via the Google Cloud Console interface or, alternatively, install and set up the gcloud CLI for command-line access and management .
You can achieve this on Ubuntu by following the steps below:
1curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-470.0.0-linux-x86_64.tar.gz
1tar -xf google-cloud-cli-470.0.0-linux-x86_64.tar.gz
1./google-cloud-sdk/install.sh
1Modify profile to update your $PATH and enable shell command completion?
2Do you want to continue (Y/n)?
Type Y
and hit Enter.
1Enter a path to an rc file to update, or leave blank to use [/home/Dipak/.bashrc]:
Just hit Enter to proceed with the default option.
Now you have successfully installed the gcloud CLI on your system.
1gcloud init
You will be prompted:
1You must log in to continue. Would you like to log in (Y/n)?
Type Y and hit Enter.
Then, return to your terminal. Inside the terminal, you will be prompted to select a numeric value corresponding to the project you want to configure with the gcloud CLI.
You will then be asked:
1Do you want to configure a default Compute Region and Zone ? (Y/n)?
Following these steps ensures that your gcloud CLI is properly installed, configured, and ready for use with your Google Cloud Platform projects.
1gcloud config list
1gcloud config set project PROJECT_ID
Replace PROJECT_ID
with your desired project ID.
A Google Cloud Function is a type of serverless computing service provided by Google Cloud Platform (GCP). It allows you to write small, single-purpose functions in popular programming languages such as JavaScript, Python, and Go. These functions are triggered by events, such as HTTP requests, changes in data stored in databases or storage buckets, or messages from messaging services.
In this guide,we'll show you how to create a Google Cloud Function using both the Google Cloud Console and the gcloud command-line tool.
• Runtime: Set memory allocation and CPU for your function, along with a timeout.
• Auto-scaling: Specify the minimum and maximum number of instances for optimal performance.
• Runtime Environment Variables: Optionally create runtime environment variables, skipping if you've set them at build time.
• Build Environment Variables: In the build section, set up environment variables for build time.
For Connections & Security and Image Repo settings, you can keep the default options or adjust them as needed.
After completing the settings, click "Next" to proceed to the next page, where you'll find the code section.
In the "Code" section, you'll start by selecting the runtime, which determines the programming language you'll use—options include Node.js, Java 11, Java 17, Python, and more.
Next, in the "Source Code" field, you have three options:
Choose the option that suits you best for uploading or writing your code.
After inserting your code, simply hit the "Deploy" button. To access your function, use the triggers you set up earlier. For instance, if you selected the HTTPS option during function creation, you'll find a URL provided below. Simply send a request to that URL to trigger your function.
Example:
Here's a simple guide to creating and deploying a Cloud Function using the gcloud CLI:
1gcloud config list
Ensure the correct account and project ID are set for where you want to create the function.
1gcloud functions deploy function-test-name \
2--gen2 \
3--runtime=nodejs20 \
4--region=us-central1 \
5--source=. \
6--entry-point=mongodump \
7--trigger-http \
8--memory=2GiB \
9--cpu=1 \
10--set-env-vars=PORT=8080 \
11--set-build-env-vars=PORT=8080,TEST_!=testValue \
12--max-instances=2
Here's a breakdown of the options used:
--gen2
: Specifies using the 2nd generation runtime environment.--runtime=nodejs20
: Sets the runtime to Node.js 20.--region=us-central1
: Specifies the region where the function will be deployed.--source=.
: Deploys the function from the current directory.--entry-point=mongodump
: Specifies the function's entry point.--trigger-http
: Configures the function to be triggered by HTTP requests.--memory=2GiB
: Allocates 2 GiB of memory to the function.--set-env-vars=PORT=8080
: Sets a runtime environment variable PORT
to 8080
.--cpu=1
: Assigns 1 virtual CPU to the function.--set-build-env-vars=PORT=8080,TEST_1=testValue
: Sets build time environment --set-env-vars=PORT=8080
: Sets a runtime environment variable PORT
to 8080
.--max-instances=2
: Sets maximum instances.This command will deploy your Cloud Function with the specified configurations.
After running the command, if you've selected the trigger as HTTP, it will ask whether to allow unauthenticated invocations of the new function. Simply type 'Y' for yes or 'N' for no.
Once the deployment is successful, you'll receive a URL to trigger your function.
If you haven't allowed or unable to get url, you can check the details of your function using the command:
1gcloud functions describe function-test-name --region=us-central1
Replace "function-test-name" with the actual name of your function.
To delete your function, use this command:
1gcloud functions delete google-function-test --gen2 --region=asia-south1
After successfully deleting the function, you'll receive a confirmation message.
For a complete list of commands and options, click here.
Google Cloud Scheduler is a fully managed cron job scheduler on Google Cloud Platform. It handles all your routine jobs automatically, making sure they run smoothly and fit into your workflow without any confusion.
After successful creation of job , it's enabled by default, meaning it's ready to run according to the schedule you've defined.
Here's the command line for creating a Cloud Scheduler job using the gcloud command-line tool, along with an example:
1gcloud scheduler jobs create http my-job --schedule="0 * * * *" --uri=https://example.com \
2--location=us-central1 \
3--description="Hourly job" \
4--headers="Content-Type=application/json" \
5--http-method=GET \
6--max-retry-attempts=3 \
7--time-zone=America/Los_Angeles
(for http scheduler job)
1gcloud scheduler jobs create pubsub my-job --schedule="0 * * * *" \
2--location=us-central1 \
3--topic=pubsub_topic \
4--message-body="Test" \
5--max-retry-attempts=3 \
6--time-zone=America/Los_Angeles
(for pub/sub job scheduler job ,replace pubsub_topic to actual topic name of cloud pub/sub)
After creating a job, you can check its status, pause, resume, or delete it using these commands:
1gcloud scheduler jobs list --location=us-central1
1gcloud scheduler jobs describe my-job --location=us-central1
1gcloud scheduler jobs pause my-job --location=us-central1
You'll receive a confirmation message if the job is successfully paused.( "Job has been paused.")
1gcloud scheduler jobs resume my-job --location=us-central1
You'll receive a confirmation message if the job is successfully paused.( "Job has been resumed.")
1gcloud scheduler jobs delete my-job --location=us-central1
It will ask for confirmation to delete,after confirmation gets confirmation message.("Deleted job [my-job]")
For a complete list of commands and options, click here.
Cloud storage allows users to store and access data over the internet, providing flexibility and scalability for personal and business needs. Use cases include backup solutions for data security and collaboration platforms for seamless team workflows.
To create a Google Cloud Storage bucket:
Multi-region: Provides redundancy across multiple regions.
Dual-region: Offers redundancy across two specific regions.
Region: Stores data in a specific region.
Here's, using the gcloud command-line tool to create a Google Cloud Storage bucket with specific configurations
1gcloud storage buckets create gs://my-bucket-test-00011 \
2 --default-storage-class=standard \
3 --location=us \
4 --public-access-prevention \
5 --uniform-bucket-level-access \
6 --soft-delete-duration=7d
After creating your bucket, if you want it to be accessible to the public on the internet, run the following command:
1gcloud storage buckets add-iam-policy-binding gs://my-bucket-test-00011 --member=allUsers --role=roles/storage.objectViewer
This command grants public access to view objects in your bucket.
1gcloud storage buckets describe gs://my-bucket-test-00011
1gcloud storage buckets delete gs://my-bucket-test-00011
1gcloud storage buckets list
For a complete list of commands and options, click here.
1npm install @google-cloud/storage
1const { Storage } = require('@google-cloud/storage');
2
3// Creates a client
4 const storage = new Storage({
5 keyFilename: "key.json",
6 });
upload()
method on the bucket object to upload the file. 1 const options = {
2 destination: "test/new-image.png", // desired destination directory and filename in the bucket , optional
3 metadata: { // optional
4 metadata: {
5 event: "Fall trip to the zoo",
6 },
7 },
8 };
9 // Lists files in the bucket
10 const files = await storage
11 .bucket("my-test-bucket-00011")
12 .upload(
13 "filename",
14 options,
15 (error, file) => {
16 if (file) {
17 console.log("file ", file);
18 }
19 }
20 );
Provide the filename, upload options, and handle any errors or success messages accordingly.
getFiles()
method to get files/objects of bucket .1const files = await storage.bucket("my-test-bucket-00011").getFiles();
file()
method to get specific file/object from bucket .1const file = await storage.bucket("my-test-bucket-00011").file('filename');
delete()
method to get specific file/object from bucket .1const file = await storage.bucket("my-test-bucket-00011").file('filename').delete();
Google Cloud Run is a serverless platform that lets you run your applications in containers without managing servers. It automatically scales your app based on traffic and you only pay for the resources used when your app is running. This makes it easy to deploy and manage applications efficiently. This makes it easy to deploy and manage applications efficiently, especially for backend services and APIs.
1FROM node:18-alpine
2
3# Create app directory
4WORKDIR /usr/src/app
5
6# A wildcard is used to ensure both package.json AND package-lock.json are copied
7COPY package*.json ./
8
9# Install app dependencies
10RUN npm install
11
12# Bundle app source
13COPY . .
14
15# Creates a "dist" folder with the production build
16RUN npm run build
17
18# Start the server using the production build
19CMD [ "npm","run", "start:prod" ]
1docker build -t gcr.io/google-cloud-project-id/test-application .
gcr.io
: The domain for Google Container Registry.google-cloud-project-id
: Google Cloud project ID. This uniquely identifies your project within Google Cloud Platform.test-application
: The name of your Docker image.1docker push gcr.io/google-cloud-project-id/test-application
if it gets any authentication error then run
1gcloud auth configure-docker
or
1gcloud auth configure-docker gcr.io
To create a Google Cloud Run service:
Artifact Registry: Create a repository and store your image there if using this option.
Container Registry: Select this option since we have already pushed our image here.
In the "Authentication" section, you have two options:
If your service needs to be accessible publicly (e.g., an API that you want to call from a browser or Postman), select "Allow unauthenticated invocations."
Note: To enable "Allow unauthenticated invocations," you need admin access or run.services.setIamPolicy
permission in the IAM policy.
In the "CPU allocation and pricing" section, you have two options:
For now, select the default setting: "CPU is only allocated during request processing."
In the "Ingress control" section, you have two options:
Select the default setting: "All."
Unfold the Container(s), volumes, networking, security section: Navigate to the section in your deployment interface where you can manage containers, volumes, networking, and security settings.
Under Container tab, find SETTINGS, VARIABLES AND SECRETS, VOLUME MOUNTS: These are separate sections where you can configure various aspects related to your container.
Once configurations are complete, click "Done" to save your settings and proceed with deployment.
Go through all the configured values to ensure correctness. Click the "Create" button to finalize the deployment.
After deployment, you will receive the URL for accessing your application.
First, you need to get the fully qualified digest of the Docker image you have pushed. You can do this by describing the container image using the gcloud command.
1gcloud container images describe gcr.io/google-cloud-project-id/test-application
In the output of the above command, look for the digest which will be in the format:
gcr.io/google-cloud-project-id/test-application@sha256:<sha_value>
Use the fully qualified digest you obtained in Step 2 to deploy the image to Google Cloud Run. Replace <sha_value> with the actual SHA value from the previous step.
1gcloud run deploy test-application \
2--image=gcr.io/google-cloud-project-id/test-application@sha256:f42563567(random sha value) \
3--allow-unauthenticated \
4--port=8080 \
5--max-instances=3 \
6--region=us-central1 \
7--set-env-vars='TEST_ENV=test value'
8
After executing the deploy command, you will get the URL of your deployed service in the output. This URL can be used to access your deployed application.
Step-by-step guide to delete a service .
To delete a specific service, use the gcloud run services delete command. You need to specify the service name and the region.
1gcloud run services delete test-application --region us-central1
After running the command, you will be prompted with:
1Do you want to continue (Y/n)?
Type Y and hit Enter to confirm the deletion.
Once the service is successfully deleted, you will see the following message in the output:
1Deleted service [test-application]
For a complete list of commands and options, click here.
Using Google Cloud Platform (GCP) for application development provides great scalability, flexibility, and tools to make your workflow easier. Take advantage of GCP's powerful features to create and deliver excellent user experiences.
There's a lot to cover in this topic, so if you have any questions or need more help, feel free to reach out. Happy coding!