1. 總覽
簡介
在本程式碼研究室中,您將瞭解如何部署使用多個容器的 Cloud Run 服務。您將建立一個 node.js 應用程式做為 Cloud Run 進入容器,並建立另一個 node.js 應用程式做為 Sidecar。
技術總覽
在 Cloud Run 執行個體中使用多個容器時,其中一個容器會做為網頁進入的主要容器。一或多個額外容器稱為 Sidecar。
多個容器之間有兩種通訊方式:
- 容器共用 localhost 網路介面,因此所有容器都能監聽通訊埠,例如 localhost:port。
- 您也可以使用記憶體內磁碟區,並將其掛接至容器,藉此共用檔案。
用途
由於 Cloud Run 執行個體中的所有容器都會共用本機主機網路介面,因此您可以在主要容器前方使用 Sidecar 代理要求。這類 Proxy 會攔截要求並轉送至適當的端點,為用戶端與伺服器之間的應用程式流量提供額外的抽象層,進而提升效率。舉例來說,您可以從 DockerHub 使用官方 Nginx 映像檔 (如這裡所示)。
由於多個容器可以透過共用磁碟區共用檔案來通訊,因此您可以將各種 Sidecar 應用程式新增至服務。舉例來說,您可以檢測 Cloud Run 服務,使用 OpenTelemetry 等自訂代理程式匯出記錄、指標和追蹤記錄 (OpenTelemetry 範例)。另一個例子是使用 Sidecar 連線至 Cloud Spanner PostgreSQL 資料庫 (Cloud Spanner PostgreSQL 範例)。
本程式碼研究室中的範例
在本程式碼研究室中,您會先部署 Cloud Run 服務,讓 Ingress 容器透過本機主機連接埠與 Sidecar 通訊。接著,您將更新 Ingress 容器和 Sidecar,透過磁碟區掛接共用檔案。
課程內容
- 如何建立使用補充資訊的容器
- Ingress 容器如何使用 localhost 與補充資訊通訊
- 如何透過掛接的磁碟區,讓 Ingress 容器和 Sidecar 共用檔案
2. 設定和需求
必要條件
- 您已登入 Cloud Console。
- 您先前已部署 Cloud Run 服務。舉例來說,您可以按照從原始碼部署網路服務的快速入門導覽課程開始操作。
啟用 Cloud Shell
- 在 Cloud 控制台,點選「啟用 Cloud Shell」 圖示
。

如果您是首次啟動 Cloud Shell,系統會顯示中繼畫面,說明這個指令列環境。如果出現中繼畫面,請按一下「繼續」。

佈建並連至 Cloud Shell 預計只需要幾分鐘。

這部虛擬機器已載入所有必要的開發工具,並提供永久的 5 GB 主目錄,而且可在 Google Cloud 運作,大幅提升網路效能並強化驗證功能。本程式碼研究室幾乎所有工作都可在瀏覽器上完成。
連至 Cloud Shell 後,您應該會看到驗證已完成,專案也已設為獲派的專案 ID。
- 在 Cloud Shell 中執行下列指令,確認您已通過驗證:
gcloud auth list
指令輸出
Credentialed Accounts
ACTIVE ACCOUNT
* <my_account>@<my_domain.com>
To set the active account, run:
$ gcloud config set account `ACCOUNT`
- 在 Cloud Shell 中執行下列指令,確認 gcloud 指令知道您的專案:
gcloud config list project
指令輸出
[core] project = <PROJECT_ID>
如未設定,請輸入下列指令手動設定專案:
gcloud config set project <PROJECT_ID>
指令輸出
Updated property [core/project].
3. 建立 Ingress 應用程式
設定環境變數
在本程式碼研究室中,您將建立幾個環境變數,提升本程式碼研究室所用 gcloud 指令的可讀性。
REGION=<YOUR-REGION> PROJECT_ID=<YOUR-PROJECT-ID> SERVICE_NAME=sidecar-codelab REPO_NAME=sidecar-codelab
建立 ArtifactRegistry 存放區來儲存容器映像檔
您可以在 Artifact Registry 中建立存放區,儲存本程式碼研究室的容器映像檔。
gcloud artifacts repositories create $REPO_NAME --repository-format=docker \ --location=$REGION --description="sidecar codelab"
接著,請建立 package.json 檔案,並加入以下內容:
{
"name": "sidecar-codelab",
"version": "1.0.0",
"private": true,
"description": "demonstrates how to use sidecars in cloud run",
"main": "index.js",
"author": "Google LLC",
"license": "Apache-2.0",
"scripts": {
"start": "node ingress.js"
},
"dependencies": {
"axios": "^1.6.2",
"express": "^4.18.2"
}
}
現在建立名為 ingress.js 的檔案,並加入下列內容:
const express = require('express');
const app = express();
const axios = require("axios");
app.get('/', async (req, res) => {
let response = await axios.get("http://localhost:5000");
res.send("The sidecar says: " + response.data);
});
const port = parseInt(process.env.PORT) || 8080;
app.listen(port, () => {
console.log(`Ingress container listening on port ${port}`);
});
為 Ingress 容器建立 Dockerfile
FROM node:20.10.0-slim WORKDIR /usr/src/app COPY package*.json ./ RUN npm install --production # Copy local code to the container image. COPY . . # Run the web service on container startup. ENV PORT=8080 CMD [ "npm", "start" ]
並為 Ingress 容器建立 ``.dockerignore` 檔案。
# Exclude locally installed dependencies node_modules/ # Exclude "build-time" ignore files. .dockerignore .gcloudignore # Exclude git history and configuration. .gitignore
現在執行下列指令,即可建構 Ingress 容器的映像檔:
gcloud builds submit --tag $REGION-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/ingress:latest
4. 建立 Sidecar 應用程式
在本節中,您將建立第二個 node.js 應用程式,做為 Cloud Run 服務中的 Sidecar。
前往 Sidecar 目錄。
cd ../sidecar
建立 package.json 檔案,並加入以下內容:
{
"name": "sidecar-codelab",
"version": "1.0.0",
"private": true,
"description": "demonstrates how to use sidecars in cloud run",
"main": "index.js",
"author": "Google LLC",
"license": "Apache-2.0",
"scripts": {
"start": "node sidecar.js"
},
"dependencies": {
"axios": "^1.6.2",
"express": "^4.18.2"
}
}
現在建立名為 sidecar.js 的檔案,並加入下列內容:
const express = require('express');
const app = express();
app.get('/', async (req, res) => {
res.send("Hello ingress container! I'm the sidecar.");
});
const port = parseInt(process.env.PORT || 5000);
app.listen(port, () => {
console.log(`Sidecar container listening on port ${port}`);
});
為 Sidecar 容器建立 Dockerfile
FROM node:20.10.0-slim WORKDIR /usr/src/app COPY package*.json ./ RUN npm install --production # Copy local code to the container image. COPY . . # Run the web service on container startup. ENV PORT=5000 CMD [ "npm", "start" ]
並為 Sidecar 容器建立 ``.dockerignore` 檔案。
# Exclude locally installed dependencies node_modules/ # Exclude "build-time" ignore files. .dockerignore .gcloudignore # Exclude git history and configuration. .gitignore
現在執行下列指令,即可建構 Ingress 容器的映像檔:
gcloud builds submit --tag $REGION-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/sidecar:latest
部署 Cloud Run 服務
您將使用 YAML 檔案部署 Cloud Run 服務。
前往上層目錄。
cd ..
建立名為 sidecar-codelab.yaml 的檔案,並加入以下內容:
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
annotations:
name: sidecar-codelab
labels:
cloud.googleapis.com/location: "<YOUR_REGION>"
spec:
template:
spec:
containers:
- image: "<YOUR_REGION>-docker.pkg.dev/<YOUR_PROJECT_ID>/sidecar-codelab/ingress:latest"
ports:
- containerPort: 8080
- image: "<YOUR_REGION>-docker.pkg.dev/<YOUR_PROJECT_ID>/sidecar-codelab/sidecar:latest"
env:
- name: PORT
value: "5000"
然後使用下列指令部署服務。由於磁碟區掛接功能為公開預先發布版,因此您必須使用 gcloud Beta 版。
gcloud beta run services replace sidecar-codelab.yaml
部署完成後,請將服務網址儲存至環境變數。
SERVICE_URL=$(gcloud run services describe $SERVICE_NAME --platform managed --region $REGION --format 'value(status.url)')
5. 呼叫 Cloud Run 服務
現在只要提供身分識別權杖,即可呼叫服務。
curl -X GET -H "Authorization: Bearer $(gcloud auth print-identity-token)" ${SERVICE_URL}
結果應類似下方的輸出範例:
The sidecar says: Hello ingress container! I'm the sidecar.
6. 透過磁碟區掛接項目共用檔案
在本節中,您將更新容器,透過磁碟區掛接共用檔案。在本範例中,輸入容器會寫入共用磁碟區上的檔案。Sidecar 會讀取檔案,並將內容傳回 Ingress 容器。
首先,請更新 Ingress 容器程式碼。前往 Ingress 目錄。
cd ../ingress
然後將 ingress.js 檔案的內容替換為下列內容:
const express = require('express');
const app = express();
const fs = require('fs');
const axios = require("axios");
const filename = "test.txt"
let path = "/my-volume-mount";
app.use(path, express.static(path));
try {
fs.writeFileSync(`${path}/${filename}`, "The ingress container created this file.");
} catch (err) {
console.error(err);
}
app.get('/', async (req, res) => {
let response = await axios.get("http://localhost:5000");
res.send("The sidecar says: " + response.data);
});
const port = parseInt(process.env.PORT) || 8080;
app.listen(port, () => {
console.log(`Ingress container listening on port ${port}`);
});
執行下列指令,為 Ingress 容器建構新映像檔:
gcloud builds submit --tag $REGION-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/ingress:latest
現在請前往 Sidecar 目錄:
cd ../sidecar
並將 sidecar.js 更新為下列內容:
const express = require('express');
const app = express();
const fs = require('fs');
const filename = "test.txt"
let path = "/my-volume-mount";
app.use(path, express.static(path));
async function readFile() {
try {
return await fs.readFileSync(`${path}/${filename}`, { encoding: 'utf8' });
} catch (err) {
console.log(err);
}
}
app.get('/', async (req, res) => {
let contents = await readFile();
res.send(contents);
});
const port = parseInt(process.env.PORT || 5000);
app.listen(port, () => {
console.log(`Sidecar container listening on port ${port}`);
});
執行下列指令,為 Sidecar 容器建構新映像檔:
gcloud builds submit --tag $REGION-docker.pkg.dev/$PROJECT_ID/$REPO_NAME/sidecar:latest
使用下列內容更新 sidecar-codelab.yaml,即可共用磁碟區:
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
annotations:
name: sidecar-codelab
labels:
cloud.googleapis.com/location: "<YOUR_REGION>"
spec:
template:
spec:
containers:
- image: "<YOUR_REGION>-docker.pkg.dev/<YOUR_PROJECT_ID>/sidecar-codelab/ingress:latest"
ports:
- containerPort: 8080
volumeMounts:
- mountPath: /my-volume-mount
name: in-memory-1
- image: "<YOUR_REGION>-docker.pkg.dev/<YOUR_PROJECT_ID>/sidecar-codelab/sidecar:latest"
env:
- name: PORT
value: "5000"
volumeMounts:
- mountPath: /my-volume-mount
name: in-memory-1
volumes:
- emptyDir:
medium: Memory
name: in-memory-1
部署更新後的 sidecar-codelab.yaml 檔案
gcloud beta run services replace sidecar-codelab.yaml
現在只要提供身分識別權杖,即可呼叫服務。
curl -X GET -H "Authorization: Bearer $(gcloud auth print-identity-token)" ${SERVICE_URL}
結果應類似下方的輸出範例:
The sidecar says: the ingress container created this file.
7. 恭喜!
恭喜您完成本程式碼研究室!
建議您參閱 Cloud Run 說明文件,特別是部署多重容器和使用記憶體內磁碟區掛接。
涵蓋內容
- 如何建立使用補充資訊的容器
- Ingress 容器如何使用 localhost 與補充資訊通訊
- 如何讓 Ingress 容器和 Sidecar 共用已掛接的磁碟區
8. 清理
為避免產生非預期費用 (例如,如果這個 Cloud Function 的叫用次數不慎超過免費層級的每月 Cloud Run 叫用次數配額),您可以刪除 Cloud Run 服務,或刪除您在步驟 2 中建立的專案。
如要刪除 Cloud Function,請前往 Cloud Function Cloud 控制台 (https://console.cloud.google.com/run/),然後刪除 sidecar-codelab 服務 (如果您使用其他名稱,請刪除 $SERVICE_NAME)。
如要刪除整個專案,請前往 https://console.cloud.google.com/cloud-resource-manager,選取您在步驟 2 中建立的專案,然後選擇「刪除」。刪除專案後,您必須在 Cloud SDK 中變更專案。如要查看所有可用專案的清單,請執行 gcloud projects list。