Node.js(1세대)를 사용하여 HTTP Cloud Run 함수 만들기 및 배포
이 가이드에서는 Node.js 런타임을 사용하여 Cloud Run 함수를 작성하는 과정을 설명합니다. Cloud Run Functions에는 다음과 같은 두 가지 유형이 있습니다.
- 표준 HTTP 요청에서 호출하는 HTTP 함수
- Pub/Sub 주제의 메시지 또는 Cloud Storage 버킷의 변경사항과 같이 클라우드 인프라의 이벤트를 처리하는 데 사용되는 이벤트 기반 함수
이 샘플은 간단한 HTTP 함수를 만드는 방법을 보여줍니다.
시작하기 전에
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Cloud Functions and Cloud Build APIs.
- gcloud CLI를 설치하고 초기화합니다.
gcloud
구성요소를 업데이트 및 설치합니다.gcloud components update
- 개발 환경을 준비합니다.
로컬 시스템에 함수 코드를 저장할 디렉토리를 만듭니다.
Linux 또는 Mac OS X
mkdir ~/helloworld cd ~/helloworld
Windows
mkdir %HOMEPATH%\helloworld cd %HOMEPATH%\helloworld
다음 콘텐츠로
helloworld
디렉터리에index.js
파일을 만듭니다.이 함수 예시는 HTTP 요청에 제공된 이름을 사용하여 인사말을 반환합니다. 제공된 이름이 없으면 'Hello World!'를 반환합니다.
npm
을 사용하여package.json
종속 항목 파일을 만들려면 다음 명령어를 실행하세요.npm init npm install c8 gaxios mocha sinon supertest wait-port --save-dev npm install @google-cloud/functions-framework escape-html
package.json
파일을 수동으로 빌드하려면helloworld
디렉터리에 다음 콘텐츠가 포함된package.json
파일을 만듭니다.함수 배포가 완료되면
httpsTrigger.url
속성을 기록하거나 다음 명령어를 사용하여 찾을 수 있습니다.gcloud functions describe helloHttp
예를 들면 다음과 같습니다.
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
브라우저에서 해당 URL을 방문하면 'Hello World!' 메시지가 표시됩니다.
예를 들어 다음 URL을 사용하여 HTTP 요청에 이름을 전달해 보세요.
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME
그러면 'Hello
NAME
!' 메시지가 표시됩니다.
함수 만들기
종속 항목 지정
Node.js의 종속 항목은 package.json
파일에 저장됩니다.
이 파일은 수동으로 만들거나 npm 명령어를 사용하여 만들 수 있습니다.
함수 배포하기
HTTP 트리거를 사용하여 함수를 배포하려면 helloworld
디렉터리에서 다음 명령어를 실행합니다.
gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated
--allow-unauthenticated
플래그를 사용하면 인증 없이 함수에 도달할 수 있습니다.
인증을 요청하려면 플래그를 생략합니다.
함수 테스트
로그 보기
Cloud Run Functions의 로그는 Google Cloud CLI 및 Cloud Logging UI를 사용하여 볼 수 있습니다.
명령줄 도구를 사용
gcloud CLI를 사용하여 함수 로그를 보려면
logs read
명령어 뒤에 함수 이름을 사용합니다.
gcloud functions logs read helloHttp
다음과 유사한 결과가 출력됩니다.
LEVEL NAME EXECUTION_ID TIME_UTC LOG D helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started D helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200
Logging 대시보드 사용
Google Cloud 콘솔에서도 Cloud Run Functions의 로그를 볼 수 있습니다.