文章段落
Cloud Run 是 Google 推出的全代管的無伺服器平台,並可以在上面開發及部署具備高擴充性的容器化應用程式。
本文將帶大家利用 Docker 建立一個簡易的 API Server 並部署到 Cloud Run。
準備應用程式
我們使用 Python & FastAPI 來快速製作一個簡易的 API Server。
本文章的所使用開發環境及工具
- Python 3.8
- FastAPI
- Docker
- Git
先從 GitHub Clone 一份範例程式碼到你的主機
$ git clone https://github.com/CATaiwan/cloud-run-api-demo
Clone 完畢後進入 cloud-run-api-demo 資料夾
$ cd cloud-run-api-demo
使用 Docker 在你的主機上 build image
$ docker build -t cloud-run-api-demo:latest .

完成後,接下來我們在主機上將剛建置完成的 docker image 跑起來並測試
$ docker run --rm -p 8000:8000 cloud-run-api-demo:latest

在瀏覽器上測試: http://localhost:8000

做到這裡我們的應用程式就準備完成了,
下一步我們將應用程式部署到 Cloud Run 。
部署前準備
開啟 Cloud Build Api
需要使用 Cloud Build 在 GCP 上建構 Docker image 並上傳至 GCR,
所以必需先到 GCP console 開啟 Cloud Build API。
開啟 GCP console > 選擇 Cloud Build > 點擊 Enable 按鈕。

API 開啟完畢之後就可以使用 Cloud Build 囉。
安裝 Google Cloud SDK (gcloud)
接下來步驟我們會用到 gcloud 的指令來執行,所以需要先安裝https://cloud.google.com/sdk/docs/install
部署至 Cloud Run
初始化及設定 gcloud (設定 project, 權限)
$ gcloud init
使用 Cloud build 建置 docker image 並推送到 Container Registry
$ gcloud builds submit --tag asia.gcr.io/{project_id}/cloud-run-api-demo

Cloud build 完成後就可以在 Container Registry 看到我們剛剛建置的 image

將建置好的 Docker image 部署到 Cloud Run
$ gcloud run deploy --image asia.gcr.io/{project_id}/cloud-run-api-demo \
--platform managed \
--port 8000 \
--memory 1Gi \
--timeout=2m \

部署完成後,會回傳 Service URL 在 Console 上可以直接連線做測試

從 GCP console 檢查 Cloud Run Service 有成功建置

以上就是部署 API Service 至 Cloud Run 的介紹。
Source Code : https://github.com/CATaiwan/cloud-run-api-demo