arrow_back

AHYBRID-131: Deploy to Cloud Run

로그인 가입
700개 이상의 실습 및 과정 이용하기

AHYBRID-131: Deploy to Cloud Run

실습 1시간 30분 universal_currency_alt 크레딧 5개 show_chart 중급
info 이 실습에는 학습을 지원하는 AI 도구가 통합되어 있을 수 있습니다.
700개 이상의 실습 및 과정 이용하기

Overview

In this exercise, you build a simple HelloWorld Node.js application, containerize it, and deploy it into Google's managed Cloud Run and Cloud Run for Anthos offerings.

Objectives

In this lab, you learn how to:

  • Create a basic JavaScript application and package it as a Docker container.
  • Harness Cloud Build to create a Docker image and deploy it into Container Registry.
  • Run the container in Google's fully managed Cloud Run.
  • Deploy the application to Cloud Run for Anthos.

Setup and requirements

For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.

  1. Sign in to Qwiklabs using an incognito window.

  2. Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
    There is no pause feature. You can restart if needed, but you have to start at the beginning.

  3. When ready, click Start lab.

  4. Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.

  5. Click Open Google Console.

  6. Click Use another account and copy/paste credentials for this lab into the prompts.
    If you use other credentials, you'll receive errors or incur charges.

  7. Accept the terms and skip the recovery resource page.

Task 1. Review your Anthos GKE cluster and install Cloud Run for Anthos

In this task, you review and prepare the pre-created Anthos GKE cluster to execute Cloud Run for Anthos. First, you verify that the GKE cluster is registered in an Anthos Fleet. Second, you check that Cloud Service Mesh is installed in the cluster as a pre-requisite to installing Cloud Run for Anthos. Third, you enable and install Cloud Run for Anthos in the cluster.

  1. On the Navigation menu (Navigation menu icon), click Kubernetes Engine > Clusters. Notice that a new GKE cluster has been created.

  2. Click Workloads, and verify that the cluster is running the Cloud Service Mesh components istio-ingressgateway and istiod-asm.

  3. On the Navigation menu, click Anthos > Clusters and verify that the cluster is registered and appears in the list of Anthos managed clusters.

  4. In the Cloud Platform Console, click Activate Cloud Shell The Activate Cloud Shell icon. If prompted, click Continue.

  5. In Cloud Shell, set the Zone environment variable:

    C1_ZONE={{{ project_0.default_zone| "Zone added at lab start" }}}
  6. In Cloud Shell, initialize the environment variables:

export PROJECT_ID=$(gcloud config get-value project) export C1_NAME="gke"
  1. Get the credentials for your gke GKE cluster:
gcloud container clusters get-credentials $C1_NAME --zone $C1_ZONE --project $PROJECT_ID
  1. Enable Cloud Run for Anthos on your project:
gcloud container fleet cloudrun enable --project=$PROJECT_ID
  1. Install Cloud Run for Anthos on your cluster:
gcloud container fleet cloudrun apply --gke-cluster=$C1_ZONE/$C1_NAME

If this step fails, wait 30 seconds and try again.

Note: Enabling Cloud Run for Anthos takes up to 15 minute; continue with the next task. Later, you review whether the installation was successful.

Task 2. Create the Node.js application

  1. To move Cloud Shell to a new tab, click the Open in a new window icon.

  2. Create a new helloworld folder for the app, and change into it:

mkdir helloworld cd helloworld
  1. Create and edit the file package.json, and save the file:
touch package.json edit package.json

The file will be opened for editing in the Cloud Shell editor in the top half of the screen.

  1. Paste the following into package.json, and save the file:
{ "name": "knative-helloworld_js", "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.17.1" } }

In Node.js, the package.json file is used to define dependencies, key files, and general application information. This package.json file:

  • Defines an Apache licensed application named knative-helloworld_js.
  • Sets the main starting file as index.js.
  • Defines the script "start" so that it executes the index.js file. If you test locally, npm start would cause this code to execute. Node is essentially the JavaScript engine that's part of Chrome.
  • Sets up a runtime dependency on express version 4.17.1 or higher, if bug fixes are available.
  1. Create and edit the application's main execution file index.js:
touch index.js edit index.js
  1. Paste the following code into index.js, and save the file:
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); });

Express.js is a lightweight JavaScript based web server. This code:

  • Creates an Express web server instance.
  • Sets it up to listen on whatever port is configured in the PORT environment variable, or port 8080 if PORT is empty.
  • Waits for requests coming into the server's root (/).

When a request comes to root, the code:

  • Logs a message to the console (Cloud Operations).
  • Returns the message "Hello target," where target is either what's configured in the TARGET environment variable, or 'World'.

Test the application

  1. Use the node package manager to load all the application dependencies:
npm install

A node_modules folder is created. All the dependencies, and the dependencies of the dependencies, are loaded into that folder.

  1. Execute the code:
npm start

The server is now waiting for a request to port 8080.

  1. Click Web preview, and then click Preview on port 8080.

Preview on port 8080 option highlighted within the web preview menu.

  1. To close the "Hello World" browser tab and stop Express, click into the Cloud Shell prompt and press CTRL + C.

Turn the application into a container

  1. Create and edit a Dockerfile to define a containerized version of the application:
touch Dockerfile edit Dockerfile
  1. Paste the following into the Dockerfile, and save the file:
FROM node:alpine WORKDIR /usr/src/app COPY package*.json ./ RUN npm install --only=production COPY . . CMD [ "npm", "start" ]

The code:

  • Creates a new container from the node alpine image.
  • Sets the WORKDIR to /user/scr/app. Subsequent file commands will be relative to this folder.
  • Copies the package.json and package-lock.json into the WORKDIR.
  • Just as when you did testing, runs npm install, but only installs production dependencies and ignores any dev dependencies that might be listed (none in this case).
  • Copies any files from the current folder into the WORKDIR.
  • When the container is launched, executes the CMD npm start.
  1. The npm installation generated some files you don't need copied into your container. Create a .dockerignore file to tell Docker which files to ignore:

    touch .dockerignore edit .dockerignore
  2. Paste the following code into .dockerignore, and save the file:

    Dockerfile README.md node_modules npm-debug.log
  3. Use Cloud Build to create the Docker image and push it to your project's Container Registry, under the name helloworld:

    export PROJECT=$(gcloud config list --format 'value(core.project)') gcloud builds submit --tag gcr.io/$PROJECT/helloworld
  4. When the process completes, view the image in Container Registry in the helloworld folder.

Task 3. Deploy helloworld to Cloud Run

  1. To enable the Cloud Run service in your project, enter the following code in Cloud Shell:

    gcloud services enable run.googleapis.com
  2. In the Google Cloud console, navigate to Cloud Run.

  3. Click Create Service to create a new service.

  4. To populate the Container image URL field, click Select and choose the latest image from your helloworld repository.

  5. Leave the Service name as helloworld.

  6. Leave Region as us-central1 (Iowa).

  7. Scroll down to Autoscaling, and set the Maximum number of instances to 4.

  8. Under Authentication, select Allow unauthenticated invocations.

  9. Click Container, Networking, Security, and investigate the different options to manage your container workload, set up environment variables, or connect your container to a Cloud SQL instance or via a VCP Connector to your private VPC.

  10. Click Create and wait for the service to come up.

  11. When an URL is displayed, click it to test the service.

  12. To deploy a new revision, click Edit & Deploy New Version.

  13. Under Environment variables, click Add Variable.

  14. For Name1 type ENV, and for Value type your name.

  15. Click Deploy.

  16. When the new service revision finishes deploying and the new version starts receiving 100% of the traffic, re-test your application. What changed?

Congratulations! You have created and deployed a Node.js application to fully managed Cloud Run.

Task 4. Deploy helloworld into Cloud Run for Anthos

  1. On the Navigation menu, click Kubernetes Engine > Workloads. Notice that several workloads have been created in the knative-serving namespace to run your Cloud Run for Anthos services.

  2. On the Navigation menu, click Anthos > Clusters, and click on your cluster to verify that Cloud Run for Anthos is enabled.

  3. On the Navigation menu, click Kubernetes Engine > Application. Click Go to list of services and click Create Service to create a new service.

  4. Configure these settings for Service settings. Note that the gke might take a few minutes to be ready before you can schedule Cloud Run workloads.

    Property Value
    Available Anthos GKE clusters gke selected
    Namespace default
    Service name helloworld-gke
Note: You can also select the Kubernetes Namespace that you want to deploy your Cloud Run container in. For this lab, use the default namespace.
  1. Click Next, and then paste your helloworld image URL(Example URL: gcr.io/qwiklabs-gcp-00-28785963622a/helloworld).

  2. Click Next, and then select External. This invokes the service through the internet.

  3. Click Create.

Note: After the service deploys, the generated URL is set to the nip.io base domain. This allows you to test your applications immediately. Note: For production, you must map a custom domain, which is also required to enable HTTPS and use automatic TLS certificates.
  1. Click on the URL to open your application.

Congratulations! You deployed a Node.js application to a fully configurable, custom GKE cluster using Cloud Run for Anthos.

End your lab

When you have completed your lab, click End Lab. Google Cloud Skills Boost 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.

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.

시작하기 전에

  1. 실습에서는 정해진 기간 동안 Google Cloud 프로젝트와 리소스를 만듭니다.
  2. 실습에는 시간 제한이 있으며 일시중지 기능이 없습니다. 실습을 종료하면 처음부터 다시 시작해야 합니다.
  3. 화면 왼쪽 상단에서 실습 시작을 클릭하여 시작합니다.

시크릿 브라우징 사용

  1. 실습에 입력한 사용자 이름비밀번호를 복사합니다.
  2. 비공개 모드에서 콘솔 열기를 클릭합니다.

콘솔에 로그인

    실습 사용자 인증 정보를 사용하여
  1. 로그인합니다. 다른 사용자 인증 정보를 사용하면 오류가 발생하거나 요금이 부과될 수 있습니다.
  2. 약관에 동의하고 리소스 복구 페이지를 건너뜁니다.
  3. 실습을 완료했거나 다시 시작하려고 하는 경우가 아니면 실습 종료를 클릭하지 마세요. 이 버튼을 클릭하면 작업 내용이 지워지고 프로젝트가 삭제됩니다.

현재 이 콘텐츠를 이용할 수 없습니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

감사합니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

한 번에 실습 1개만 가능

모든 기존 실습을 종료하고 이 실습을 시작할지 확인하세요.

시크릿 브라우징을 사용하여 실습 실행하기

이 실습을 실행하려면 시크릿 모드 또는 시크릿 브라우저 창을 사용하세요. 개인 계정과 학생 계정 간의 충돌로 개인 계정에 추가 요금이 발생하는 일을 방지해 줍니다.