arrow_back

Hello Cloud Run

Join Sign in

Hello Cloud Run

45 minutes 1 Credit

GSP492

Google Cloud selp-paced labs logo

894762ebb681671c.png

Overview

Cloud Run is a managed compute platform that enables you to run stateless containers that are invocable via HTTP requests. Cloud Run is serverless: it abstracts away all infrastructure management, so you can focus on what matters most — building great applications.

Knative, letting you choose to run your containers either fully managed with Cloud Run, or in your Google Kubernetes Engine cluster with Cloud Run on GKE.

The goal of this lab is for you to build a container image and deploying it to Cloud Run. In this lab, you'll learn how to get started with Cloud Run by deploying and running a stateless container serverless-ly (with the infrastructure abstracted away). Cloud Run offers a fully-managed option as well as the ability to run on top of a GKE cluster.

Setup and Requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
__Note:__ Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
__Note:__ If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is a panel populated with the temporary credentials that you must use for this lab.

    Open Google Console

  2. Copy the username, and then click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Sign in

    Tip: Open the tabs in separate windows, side-by-side.

  3. In the Sign in page, paste the username that you copied from the left panel. Then copy and paste the password.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Training credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).

  4. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

In the Cloud Console, in the top right toolbar, click the Activate Cloud Shell button.

Cloud Shell icon

Click Continue.

cloudshell_continue.png

It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:

Cloud Shell Terminal

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

You can list the active account name with this command:

gcloud auth list

(Output)

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`

You can list the project ID with this command:

gcloud config list project

(Output)

[core] project = <project_ID>

(Example output)

[core] project = qwiklabs-gcp-44776a13dea667a6

Enable the Cloud Run API

From Cloud Shell, enable the Cloud Run API :

gcloud services enable run.googleapis.com

This should produce a successful message similar to this one:

Operation "operations/acf.cc11852d-40af-47ad-9d59-477a12847c9e" finished successfully. Note: You can also enable the API using the APIs & Services section of the console.

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully enable the Cloud Run API, you will see an assessment score.

Enable the Cloud Run API

Write the sample application

First, you will build a simple express-based NodeJS application responding to HTTP requests.

In Cloud Shell create a new directory named helloworld-nodejs, then change into that directory:

mkdir helloworld-nodejs cd helloworld-nodejs

Next you'll be creating and editing files. To edit files, use vi, emac, nano or the Cloud Shell Code Editor by clicking on the Open editor icon in Cloud Shell.

editor.png

Create a package.json file, then add the following content to it:

{ "name": "cloudrun-helloworld", "version": "1.0.0", "description": "Simple hello world sample in Node", "main": "index.js", "scripts": { "start": "node index.js" }, "author": "", "license": "Apache-2.0", "dependencies": { "express": "^4.16.4" } }

Most importantly, the file above contains a start script command and a dependency on the Express web application framework.

Next, in the same directory, create a index.js file, and copy the following lines into it:

const express = require('express'); const app = express(); app.get('/', (req, res) => { console.log('Hello world received a request.'); const target = process.env.TARGET || 'World'; res.send(`Hello ${target}!`); }); const port = process.env.PORT || 8080; app.listen(port, () => { console.log('Hello world listening on port', port); });

This code creates a basic web server that listens on the port defined by the PORT environment variable. Your app is now finished and ready to be containerized and uploaded to Container Registry.

Many other languages are documented to get started with Cloud Run. You can find instructions for Go, Python, Java, PHP, Ruby, Shell scripts, and others here: https://cloud.google.com/run/docs/quickstarts/build-and-deploy

Containerize your app and upload it to Container Registry

To containerize the sample app, create a new file named Dockerfile in the same directory as the source files, and add the following content:

# Use the official Node.js 10 image. # https://hub.docker.com/_/node FROM node:10 # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. # Copying this separately prevents re-running npm install on every code change. COPY package*.json ./ # Install production dependencies. RUN npm install --only=production # Copy local code to the container image. COPY . . # Run the web service on container startup. CMD [ "npm", "start" ]

Get your Project ID by running the following, you'll need it for the next step:

gcloud config get-value project

Now, build your container image using Cloud Build by running the following command from the directory containing the Dockerfile, adding your Project-ID from the last output:

gcloud builds submit --tag gcr.io/[PROJECT-ID]/helloworld

Cloud Build is a service that executes your builds on Google Cloud. It executes a series of build steps, where each build step is run in a Docker container to produce your application container (or other artifacts) and push it to Cloud Registry, all in one command.

Once pushed to the registry, you will see a SUCCESS message containing the image name (gcr.io/[PROJECT-ID]/helloworld). The image is stored in Container Registry and can be re-used if desired.

List all the container images associated with your current project using this command :

gcloud container images list

To run and test the application locally from Cloud Shell, start it using this standard docker command and make sure to replace your project id.

docker run -d -p 8080:8080 gcr.io/[PROJECT-ID]/helloworld

In the Cloud Shell window, click on Web preview and select "Preview on port 8080".

web_preview.png

This should open a browser window showing the "Hello World!" message. You could also simply use curl localhost:8080.

Note: If the docker command cannot pull the remote container image then try running this : gcloud auth configure-docker

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully deployed containerize your app and upload it to Container Registry, you will see an assessment score.

Containerize your app and upload it to Container Registry

Deploy to Cloud Run

Deploying your containerized application to Cloud Run is done using the following command adding your Project-ID:

gcloud run deploy --image gcr.io/[PROJECT-ID]/helloworld --max-instances=3

When prompted:

  • confirm the service name by pressing Enter
  • select your region ( us-central1)
  • respond y to allow unauthenticated invocations (that last step is important and can also be avoided by using the --allow-unauthenticated deploy option).

Wait a few moments until the deployment is complete.

On success, the command line displays the service URL:

Done Service [helloworld] revision [helloworld-00001-foz] has been deployed and is serving 100 percent of traffic. Service URL: https://helloworld-rgewyhld7q-uc.a.run.app

You can now visit your deployed container by opening the service URL in any browser window:

c43301c68f16c08c.png

Test Completed Task

Click Check my progress to verify your performed task. If you have successfully deployed your app to Cloud Run, you will see an assessment score.

Deploy to Cloud Run

For this lab you used the gcloud command-line. Cloud Run is also available via Cloud Console.

From the Navigation menu, in the Compute section, click Cloud Run and you should see your helloworld service listed:

39a252020a4b78.png

Tear down

Qwiklabs will take care of shutting down all the resources we've used so far, but here's what you would need to do on your own environment to save on cost and to be a good cloud citizen.

While Cloud Run does not charge when the service is not in use, you might still be charged for storing the built container image.

You can either decide to delete your Google Cloud project to avoid incurring charges, which will stop billing for all the resources used within that project, or simply delete your helloworld image using this command. Make sure to replace your project id.

gcloud container images delete gcr.io/[PROJECT-ID]/helloworld

To delete the Cloud Run service, use this command:

gcloud beta run services delete helloworld

Congratulations

Congratulations! You have just deployed an application packaged in a container image to Cloud Run. Cloud Run automatically and horizontally scales your container image to handle the received requests, then scales down when demand decreases. In your own environment, you only pay for the CPU, memory, and networking consumed during request handling.

End your lab

When you have completed your lab, click End Lab. Qwiklabs removes the resources you’ve used and cleans the account for you.

You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.

The number of stars indicates the following:

  • 1 star = Very dissatisfied
  • 2 stars = Dissatisfied
  • 3 stars = Neutral
  • 4 stars = Satisfied
  • 5 stars = Very satisfied

You can close the dialog box if you don't want to provide feedback.

For feedback, suggestions, or corrections, please use the Support tab.

Next Steps / Learn More

For more information on building a stateless HTTP container suitable for Cloud Run from code source and pushing it to Container Registry, see:

Google Cloud Training & Certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated May 9, 2022
Lab Last Tested May 9, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.