arrow_back

Deploy Your Website on Cloud Run

Join Sign in

Deploy Your Website on Cloud Run

1 hour 1 Credit

GSP659

Google Cloud self-paced labs logo

Overview

Running websites can be difficult with all of the overhead of creating and managing VMs, clusters, pods, services, etc. This is fine for larger, multi-tiered applications, but if you are just trying to get your website deployed and visible, it's a lot of overhead.

With Cloud Run, Google Cloud's implementation of Google's Knative framework, you can manage and deploy your website without any of the infrastructure overhead you experience with a VM or pure Kubernetes-based deployments. Not only is this a simpler approach from a management perspective, it also gives you the ability to "scale to zero" when there are no requests coming into your website.

Cloud Run brings "serverless" development to containers and can be run either on your own Google Kubernetes Engine (GKE) clusters or on a fully managed PaaS solution provided by Cloud Run. You will be running the latter scenario in this lab.

The exercises are ordered to reflect a common cloud developer experience:

  1. Create a Docker container from your application

  2. Deploy the container to Cloud Run

  3. Modify the website

  4. Roll out a new version with zero downtime

Architecture diagram

Below you can see the flow of the deployment and Cloud Run hosting.

Begin with a Docker image created via Cloud Build, which gets triggered from Cloud Shell, then deploy the image out to Cloud Run from a command in Cloud Shell.

overview diagram

What you'll learn

  • How to build a Docker image using Cloud Build and upload it to Artifact Registry

  • How to deploy Docker images to Cloud Run

  • How to manage Cloud Run deployments

  • How to setup an endpoint for an application on Cloud Run

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 the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

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

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. 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.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

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.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

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

  1. (Optional) You can list the active account name with this command:

gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) 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 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Clone the source repository

Since you are deploying an existing website, you just need to clone the source, so you can focus on creating Docker images and deploying to Cloud Run.

  1. Open a new Cloud Shell window and run the following commands to clone the git repository and change to the appropriate directory.

git clone https://github.com/googlecodelabs/monolith-to-microservices.git cd ~/monolith-to-microservices
  1. Run the following command to install the NodeJS dependencies so you can test the application before deploying:

./setup.sh

This will take a few minutes to run. You will see a success message when it finishes.

  1. Test your application by running the following command to start the web server:

cd ~/monolith-to-microservices/monolith npm start

Output:

Monolith listening on port 8080!
  1. Preview your application by clicking the web preview icon and selecting Preview on port 8080.

overview diagram

This should open a new window where you can see your Fancy Store web page in action.

hostwebsite fancystore

  1. Close this window after viewing the website, and stop the web server process by pressing CTRL+C in Cloud Shell.

Create a Docker container with Cloud Build

Now that you have the source files ready to go, it is time to Dockerize your application!

Normally you would have to take a two step approach that entails building a docker container and pushing it to a registry to store the image for GKE to pull from. Make life easier and use Cloud Build to build the Docker container and put the image in Artifact Registry with a single command! To view the manual process of creating a Docker file and pushing it, go here.

Cloud Build will compress the files from the directory and move them to a Cloud Storage bucket. The build process will then take all the files from the bucket and use the Dockerfile, which is present in the same directory, to run the Docker build process.

Create the target Docker repository

You must create a repository before you can push any images to it. Pushing an image can't trigger creation of a repository and the Cloud Build service account does not have permissions to create repositories.

  1. From the Navigation Menu, under CI/CD navigate to Artifact Registry > Repositories.

  2. Click Create Repository.

  3. Specify monolith-demo as the repository name.

  4. Choose Docker as the format.

  5. Under Location Type, select Region and then choose the location us-central1.

  6. Click Create.

Configure authentication

Before you can push or pull images, configure Docker to use the Google Cloud CLI to authenticate requests to Artifact Registry.

  1. To set up authentication to Docker repositories in the region us-central1, run the following command in Cloud Shell:

gcloud auth configure-docker us-central1-docker.pkg.dev

The command updates your Docker configuration. You can now connect with Artifact Registry in your Google Cloud project to push and pull images.

Deploy the image

You will now deploy the image that was built earlier.

  1. First you need to enable the Cloud Build, Artifact Registry, and Cloud Run APIs. Run the following command to enable them:

gcloud services enable artifactregistry.googleapis.com \ cloudbuild.googleapis.com \ run.googleapis.com
  1. After the APIs are enabled, run the following command to start the build process:

gcloud builds submit --tag us-central1-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/monolith-demo/monolith:1.0.0 Note: This process will take a few minutes.
  1. To view your build history, or watch the process in real time, in the Console, from the Navigation menu click Cloud Build > History. Here you can see a list of all your builds; there should only be 1 that you just created.

4c753ede203255f6.png

If you click on the Build ID, you can see all the details for that build including the log output.

From the Build Details page you can view the container image that was created by clicking the Execution Details tab, then clicking on on the image link.

Build_details.png

Click Check my progress to verify the objective. Create Docker Container with Google Cloud Build

Deploy the container to Cloud Run

Now that you have containerized your website and pushed the container to Artifact Registry, it is time to deploy to Cloud Run!

There are two approaches for deploying to Cloud Run:

  • Managed Cloud Run: The Platform as a Service model where all container lifecycle is managed by the Cloud Run product itself. You'll be using this approach in this lab.

  • Cloud Run on GKE: Cloud Run with an additional layer of control which allows you to bring your own clusters & pods from GKE. You can read more about it here.

  1. Run the following command to deploy the image to Cloud Run. When asked to allow unauthenticated invocations to [monolith] type Y.

gcloud run deploy monolith --image us-central1-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/monolith-demo/monolith:1.0.0 --region us-central1

Click Check my progress to verify the objective. Deploy Container To Cloud Run

Verify deployment

To verify the deployment was created successfully, run the following command:

gcloud run services list Note: It may take a few moments for the pod status to be Running.

Output:

✔ SERVICE: monolith REGION: us-central1 URL: https://monolith-2cxtmp4m2q-uc.a.run.app LAST DEPLOYED BY: student-02-aa7a5aed362d@qwiklabs.net LAST DEPLOYED AT: 2022-08-19T19:16:14.351981Z

This output shows several things. You can see the deployment, as well as the user that deployed it (your email) and the URL you can use to access the app. Looks like everything was created successfully!

Click on the URL provided in the list of services. You should see the same website you previewed locally.

Hint: You can also view your Cloud Run deployments via the Console if you navigate to Cloud Run in the Navigation menu.

Create new revision with lower concurrency

In this section you will deploy your application again, but this time adjusting one of the parameters.

By default, a Cloud Run application will have a concurrency value of 80, meaning that each container instance will serve up to 80 requests at a time. This is a big departure from the Functions-as-a-Service model, where one instance handles one request at a time.

  1. Run the following command to re-deploy the same container image with a concurrency value of 1 (just for testing), and see what happens:
gcloud run deploy monolith --image us-central1-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/monolith-demo/monolith:1.0.0 --region us-central1 --concurrency 1
  1. To see the details, from the Navigation menu, click on Cloud Run, then click on the monolith service :

7d1eed2e4728a4f2.png

  1. On the Service Details page, click on the Revisions tab. You should now see 2 revisions created.

The most recent deployment has Details on the right hand side.

monolith-revisions.png

You will see that the concurrency value has been reduced to "1".

monolith-details.png

Although this configuration is sufficient for testing, in most production scenarios you will have containers supporting multiple concurrent requests.

Click Check my progress to verify the objective. Create new revision with lower concurrency

Next, you can restore the original concurrency without re-deploying. You could set the concurrency value back to the default of "80", or you could just set the value to "0", which will remove any concurrency restrictions and set it to the default max (which happens to be 80).

  1. Run the following command to update the current revision, using a concurrency value of 80:

gcloud run deploy monolith --image us-central1-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/monolith-demo/monolith:1.0.0 --region us-central1 --concurrency 80

You will notice that another revision has been created, that traffic has now been redirected, and that the concurrency is back up to 80.

You may need to leave the Revisions tab and then return to it to see the most up to date information.

Make changes to the website

Scenario: Your marketing team has asked you to change the homepage for your site. They think it should be more informative of who your company is and what you actually sell.

Task: You will add some text to the homepage to make the marketing team happy! It looks like one of our developers already created the changes with the file name index.js.new. You can just copy this file to index.js and your changes should be reflected. Follow the instructions below to make the appropriate changes.

  1. Run the following commands to copy the updated file to the correct file name.

cd ~/monolith-to-microservices/react-app/src/pages/Home mv index.js.new index.js
  1. Print its contents to verify the changes:

cat ~/monolith-to-microservices/react-app/src/pages/Home/index.js

The resulting code should look like this:

/* Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; import Typography from "@material-ui/core/Typography"; const useStyles = makeStyles(theme => ({ root: { flexGrow: 1 }, paper: { width: "800px", margin: "0 auto", padding: theme.spacing(3, 2) } })); export default function Home() { const classes = useStyles(); return ( <div className={classes.root}> <Paper className={classes.paper}> <Typography variant="h5"> Fancy Fashion &amp; Style Online </Typography> <br /> <Typography variant="body1"> Tired of mainstream fashion ideas, popular trends and societal norms? This line of lifestyle products will help you catch up with the Fancy trend and express your personal style. Start shopping Fancy items now! </Typography> </Paper> </div> ); }

You updated the React components, but you need to build the React app to generate the static files.

  1. Run the following command to build the React app and copy it into the monolith public directory:

cd ~/monolith-to-microservices/react-app npm run build:monolith

Now that the code is updated, rebuild the Docker container and publish it to Artifact Registry. You can use the same command as before, except this time you will update the version label.

  1. Run the following command to trigger a new Cloud Build with an updated image version of 2.0.0:

cd ~/monolith-to-microservices/monolith gcloud builds submit --tag us-central1-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/monolith-demo/monolith:2.0.0

In the next section you will use this image to update your application with zero downtime.

Click Check my progress to verify the objective. Make Changes To The Website

Update website with zero downtime

The changes are complete and the marketing team is happy with your updates! It is time to update the website without interruption to the users. Cloud Run treats each deployment as a new Revision which will first be brought online, then have traffic redirected to it.

By default the latest revision will be assigned 100% of the inbound traffic for a service. It is possible to use "Routes" to allocate different percentages of traffic to different revisions within a service. Follow the instructions below to update your website.

  1. Run the following command to re-deploy the service to update the image to a new version with the following command:

gcloud run deploy monolith --image us-central1-docker.pkg.dev/${GOOGLE_CLOUD_PROJECT}/monolith-demo/monolith:2.0.0 --region us-central1

Click Check my progress to verify the objective. Update website with zero downtime

Verify deployment

  1. Validate that your deployment updated by running the following command:

gcloud run services describe monolith --platform managed --region us-central1

Output:

✔ Service monolith in region us-central1 URL: https://monolith-hl5loimtga-uc.a.run.app Ingress: all Traffic: 100% LATEST (currently monolith-00005-xum) Last updated on 2022-08-19T18:39:39.885859Z by student-02-9af04e268b9e@qwiklabs.net: Revision monolith-00005-xum Image: us-central1-docker.pkg.dev/qwiklabs-gcp-00-30d07cf3de5b/monolith-demo/monolith:2.0.0 Port: 8080 Memory: 512Mi CPU: 1000m Service account: 467160385597-compute@developer.gserviceaccount.com Concurrency: 80 Max Instances: 1 Timeout: 300s

Here you will see that the Service is now using the latest version of your image, deployed in a new revision.

To verify the changes, navigate to the external URL of the Cloud Run service, refresh the page, and notice that the application title has been updated.

  1. Run the following command to list the services and view the IP address:

gcloud beta run services list
  1. Click on the URL of the service. Your web site should now be displaying the text you just added to the homepage component!

hostwebsite-welc-fancystore-edited.png

Congratulations!

You successfully deployed, de-scaled, re-scaled, and updated your website on Cloud Run.

completion_badge_Website_on_Google_Cloud-135.png

Finish Your Quest

This self-paced lab is part of the Website on Google Cloud Quest. A Quest is a series of related labs that form a learning path. Completing this Quest earns you the badge above, to recognize your achievement. You can make your badge (or badges) public and link to them in your online resume or social media account. Enroll in a Quest and get immediate completion credit if you've taken this lab. See other available Quests.

Next Steps / Learn More

If you're not familiar with these products, here are links to learn more:

Manual Last Updated: September 22, 2022

Lab Last Tested: September 22, 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.