1. 소개
개요
Cloud Run 샌드박스는 기존 서비스 내에서 신뢰할 수 없는 코드를 실행하거나 AI 에이전트가 작성한 코드와 같은 도구를 실행할 수 있는 빠르고 안전하며 격리된 환경을 제공합니다.
이 Codelab에서는 Cloud Run 샌드박스에서 nodejs와 python을 모두 실행하는 방법을 보여줍니다. --allow-egress 플래그를 사용하여 샌드박스 내에 종속 항목을 설치하는 방법도 알아봅니다.
샌드박스에 대한 자세한 내용은 Cloud Run 샌드박스 문서, 샌드박스에서 코드 실행 방법, 블로그 게시물을 참조하세요.
학습할 내용
- Cloud Run 샌드박스에서 코드 (nodejs 및 python)를 실행하는 방법
- Cloud Run 샌드박스에서 종속 항목을 설치하는 방법
- Cloud Run에서 FastAPI를 사용하는 방법
2. 설정 및 요구사항
기본 요건
- Cloud Console에 로그인했습니다.
- 이전에 Cloud Run 서비스를 배포했습니다. 예를 들어 이 빠른 시작에 따라 Cloud Run 서비스를 배포하여 시작할 수 있습니다.
환경 변수 설정
먼저 프로젝트 ID를 구성했는지 확인합니다.
gcloud config set project <YOUR_PROJECT_ID>
다음을 실행하여 현재 프로젝트 ID를 확인할 수 있습니다.
gcloud config get project
다음으로 원하는 리전을 구성합니다.
export REGION=<YOUR_REGION>
3. 서비스 만들기
이 Codelab은 샌드박스에서 nodejs 및 python 코드를 실행하지만 모든 언어로 코드를 실행할 수 있습니다. 아래에서 배우는 것처럼 실행하는 모든 명령어 또는 도구가 컨테이너 이미지에 설치되어 있는지 확인합니다.
먼저 소스 코드의 디렉터리를 만들고 해당 디렉터리로 cd합니다.
mkdir sandbox-codelab && cd $_
다음으로 Dockerfile을 만듭니다.
FROM python:3.11-slim
# Install Node.js to run both python and nodejs in sandbox
RUN apt-get update && apt-get install -y curl \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/*
# Set working directory
WORKDIR /app
# Copy requirements and install them
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code
COPY main.py .
# Run the FastAPI application using python
CMD ["python", "main.py"]
다음으로 다음 콘텐츠가 포함된 requirements.txt 파일을 만듭니다.
fastapi
uvicorn
다음 콘텐츠가 포함된 main.py 파일을 만듭니다.
import os
import sys
import subprocess
import shlex
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import uvicorn
app = FastAPI()
def run_in_sandbox(language: str, code: str, dependency: str = None):
# Setup commands
if language == "python":
run_cmd = f"python3 -c {shlex.quote(code)}"
install_cmd = f"pip install --no-cache-dir {dependency} >&2" if dependency else ""
elif language in ("node", "nodejs"):
run_cmd = f"node -e {shlex.quote(code)}"
install_cmd = f"npm install --cache /tmp/.npm-cache {dependency} >&2" if dependency else ""
else:
raise ValueError(f"Unsupported language: {language}")
# Combine install and execution commands if dependency exists
full_inner_cmd = f"{install_cmd} && {run_cmd}" if dependency else run_cmd
# Build sandbox command
# This binary is automatically injected into the container via the --sandbox-launcher deployment flag
sandbox_cmd = [
"/usr/local/gcp/bin/sandbox",
"do",
]
if dependency:
sandbox_cmd.extend(["--write", "--allow-egress"])
sandbox_cmd.extend(["--", "/bin/bash", "-c", full_inner_cmd])
return subprocess.run(
sandbox_cmd,
capture_output=True,
text=True,
timeout=15, # Increased timeout to allow for package downloads
)
@app.get("/python")
async def execute_python():
sandbox_code = "print(20 + 45)"
try:
result = run_in_sandbox("python", sandbox_code)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.returncode,
}
except subprocess.TimeoutExpired:
return JSONResponse(status_code=408, content={"error": "Execution timed out"})
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
@app.get("/nodejs")
async def execute_nodejs():
sandbox_code = "const isOdd = require('is-odd'); console.log('Is 13 odd?', isOdd(13));"
dependency = "is-odd"
try:
result = run_in_sandbox("nodejs", sandbox_code, dependency)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.returncode,
}
except subprocess.CalledProcessError as e:
return JSONResponse(status_code=400, content={"error": f"Failed to install dependency: {e.stderr}"})
except subprocess.TimeoutExpired:
return JSONResponse(status_code=408, content={"error": "Execution timed out"})
except Exception as e:
return JSONResponse(status_code=500, content={"error": str(e)})
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
4. 배포 및 테스트
이제 Cloud Run에 배포합니다. --sandbox-launcher 플래그와 beta 출시 수준을 확인합니다.
gcloud beta run deploy sandbox-executor \
--source . \
--region $REGION \
--no-allow-unauthenticated \
--sandbox-launcher
배포되면 환경 변수에 서비스 URL을 기록합니다.
SERVICE_URL=$(gcloud run services describe sandbox-executor --region $REGION --format 'value(status.url)')
먼저 샌드박스 내에서 두 숫자를 더하는 python 엔드포인트를 호출해 봅니다.
curl -X GET $SERVICE_URL/python \
-H "Authorization: Bearer $(gcloud auth print-identity-token)"
Python 코드에 대해 다음이 반환됩니다.
{"stdout":"65\n","stderr":"","exit_code":0}
이제 종속 항목 (is-odd)을 설치하고 샌드박스에서 사용하는 nodejs 엔드포인트를 사용해 봅니다.
curl -X GET $SERVICE_URL/nodejs \
-H "Authorization: Bearer $(gcloud auth print-identity-token)"
응답에 다음이 표시됩니다 (stderr에 일부 npm 로그와 함께).
{"stdout":"Is 13 odd? true\n","stderr":"...","exit_code":0}
5. 수고하셨습니다
Codelab을 완료해 주셔서 감사합니다.
Cloud Run 샌드박스 문서와 샌드박스에서 코드를 실행하는 방법을 검토하는 것이 좋습니다.
학습한 내용
- Cloud Run 샌드박스에서 코드를 실행하는 방법
- Cloud Run 샌드박스에서 종속 항목을 설치하는 방법
- Cloud Run에서 FastAPI를 사용하는 방법
6. 정리
의도치 않은 요금이 청구되지 않도록 하려면(예: Cloud Run 서비스 sandbox-executor가 무료 등급에서 월별 Cloud Run 호출 할당량보다 더 많이 호출되는 경우) Cloud Run 서비스를 삭제하거나 2단계에서 만든 프로젝트를 삭제하면 됩니다.
Cloud Run 서비스를 삭제하려면 https://console.cloud.google.com/run/의 Cloud Console에서 Cloud Run으로 이동하여 이 Codelab에서 만든 서비스를 삭제합니다.
전체 프로젝트를 삭제하려면 https://console.cloud.google.com/cloud-resource-manager로 이동하여 2단계에서 만든 프로젝트를 선택하고 삭제를 선택합니다. 프로젝트를 삭제하면 Cloud SDK에서 프로젝트를 변경해야 합니다. gcloud projects list를 실행하여 사용 가능한 모든 프로젝트의 목록을 볼 수 있습니다.