Claude Code से GCP Cloud Run पर deploy करने की practical guide
Docker, IAM, secrets, logs और rollback के साथ Node.js API को Cloud Run पर सुरक्षित deploy करें।
Cloud Run तब बहुत उपयोगी है जब आप containerized HTTP service publish करना चाहते हैं, लेकिन Kubernetes, ECS या VM fleet चलाना नहीं चाहते। Cloud Functions या Lambda की तुलना में इसमें आपको हर चीज को छोटे functions में तोड़ना नहीं पड़ता। आप एक सामान्य Express API को Docker image बनाकर Cloud Run पर चला सकते हैं, और Google Cloud HTTPS, revisions, scaling और logs संभालता है।
इस guide में हम Claude Code की मदद से TypeScript/Express API को local development से Cloud Run तक ले जाएंगे। इसमें runnable code, Dockerfile, local test, Artifact Registry, gcloud run deploy, service account, IAM, Secret Manager, concurrency, min instances, Cloud Logging, revision rollback, cost pitfalls और deployment-review prompt शामिल हैं।
सरल भाषा में: Cloud Run वह serverless platform है जो HTTP requests के लिए containers चलाता है। Artifact Registry Docker images रखने की जगह है। Secret Manager passwords और API keys का vault है। IAM वह permission system है जो तय करता है कि कौन-सी identity कौन-सा resource access कर सकती है।
Cloud Run कब Functions या Lambda से बेहतर है
Cloud Run हर जगह बेहतर नहीं है। बहुत छोटा event handler हो तो Cloud Functions या Lambda आसान हो सकते हैं। लेकिन जब service पहले से HTTP app है, या runtime dependencies पर ज्यादा control चाहिए, तब Cloud Run बेहतर fit होता है।
| Use case | Cloud Run क्यों fit है |
|---|---|
| Webhook receiver | Stripe, GitHub या LINE webhooks को Express routes में आसानी से रखा जा सकता है |
| छोटा BFF/API server | Auth, middleware, routing और validation एक सामान्य Node.js app में रहते हैं |
| Scheduled HTTP batch endpoint | Cloud Scheduler HTTP call कर सकता है, अलग job framework जरूरी नहीं |
| हल्की AI/data API | Native dependencies और custom binaries container में रखे जा सकते हैं |
Long-running background worker के लिए CPU allocation और cost पहले review करें। Cloud Run request-driven services के लिए अच्छा है, लेकिन हर background loop के लिए default choice नहीं है।
Runnable Express service
Cloud Run container को PORT environment variable देता है। Service को वही port पढ़ना चाहिए, /health expose करना चाहिए और SIGTERM मिलने पर graceful shutdown करना चाहिए।
{
"name": "cloud-run-claude-code-api",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.19.2"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/node": "^22.10.0",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
}
}
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"]
}
import express from "express";
const app = express();
app.use(express.json());
const requiredEnv = ["DATABASE_URL", "JWT_SECRET"];
for (const key of requiredEnv) {
if (!process.env[key]) {
console.error(`Missing required environment variable: ${key}`);
process.exit(1);
}
}
app.get("/health", (_req, res) => {
res.status(200).json({ ok: true, service: "myapp-api" });
});
app.post("/webhooks/example", (req, res) => {
console.log("webhook_received", {
eventType: req.body?.type ?? "unknown",
receivedAt: new Date().toISOString()
});
res.status(202).json({ accepted: true });
});
app.get("/config-check", (_req, res) => {
res.json({
nodeEnv: process.env.NODE_ENV ?? "development",
hasDatabaseUrl: Boolean(process.env.DATABASE_URL),
hasJwtSecret: Boolean(process.env.JWT_SECRET)
});
});
const port = Number(process.env.PORT ?? 8080);
const server = app.listen(port, () => {
console.log(`listening on ${port}`);
});
process.on("SIGTERM", () => {
console.log("SIGTERM received, closing HTTP server");
server.close(() => process.exit(0));
setTimeout(() => process.exit(1), 30000).unref();
});
पहले local check करें:
npm install
DATABASE_URL="postgresql://local" JWT_SECRET="local-secret" npm run dev
curl http://localhost:8080/health
curl -X POST http://localhost:8080/webhooks/example \
-H "Content-Type: application/json" \
-d '{"type":"demo.created"}'
Dockerfile और Claude Code review
Claude Code से सिर्फ Dockerfile generate न कराएं। उसे production review दें: runtime image छोटी हो, production dependencies ही install हों, non-root user हो, .dockerignore हो, PORT support हो, और security/cost risks बताए जाएं।
claude -p "
Review and improve this Cloud Run Docker setup.
Requirements:
- Node.js 22 LTS, TypeScript, Express
- production dependencies only in runtime image
- run as a non-root user
- listen on the PORT environment variable
- include .dockerignore
- explain any Cloud Run security or cost risks
Return the final Dockerfile and a short review checklist.
"
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=8080
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=builder /app/dist ./dist
USER appuser
EXPOSE 8080
CMD ["node", "--max-old-space-size=384", "dist/index.js"]
node_modules
dist
.env
.env.*
*.log
.git
.gitignore
Dockerfile
README.md
docker build -t myapp-api:local .
docker run --rm -p 8080:8080 \
-e PORT=8080 \
-e DATABASE_URL="postgresql://local" \
-e JWT_SECRET="local-secret" \
myapp-api:local
curl http://localhost:8080/health
Artifact Registry और पहला deploy
Artifact Registry Docker image store करता है। Regional host के लिए Docker authentication configure करें, repository बनाएं और image push करें।
PROJECT_ID="my-project-123"
REGION="asia-northeast1"
REPOSITORY="myapp"
SERVICE="myapp-api"
IMAGE="$REGION-docker.pkg.dev/$PROJECT_ID/$REPOSITORY/api:v1.0.0"
gcloud config set project "$PROJECT_ID"
gcloud services enable run.googleapis.com artifactregistry.googleapis.com secretmanager.googleapis.com logging.googleapis.com
gcloud artifacts repositories create "$REPOSITORY" \
--repository-format=docker \
--location="$REGION" \
--description="Docker images for myapp"
gcloud auth configure-docker "$REGION-docker.pkg.dev"
docker build -t "$IMAGE" .
docker push "$IMAGE"
Deploy से पहले dedicated runtime service account बनाएं।
gcloud iam service-accounts create myapp-run \
--display-name="Cloud Run runtime for myapp"
SERVICE_ACCOUNT="myapp-run@$PROJECT_ID.iam.gserviceaccount.com"
gcloud run deploy "$SERVICE" \
--image "$IMAGE" \
--region "$REGION" \
--platform managed \
--service-account "$SERVICE_ACCOUNT" \
--memory 512Mi \
--cpu 1 \
--concurrency 80 \
--min-instances 0 \
--max-instances 20 \
--allow-unauthenticated \
--set-env-vars NODE_ENV=production \
--port 8080
Internal API के लिए --allow-unauthenticated हटाएं और Cloud Run Invoker role केवल जरूरी callers को दें।
Secret Manager, IAM और security
Secrets को --set-env-vars में plain text में न लिखें। उन्हें Secret Manager में रखें और Cloud Run से inject कराएं।
echo -n "postgresql://user:password@host:5432/app" | \
gcloud secrets create DATABASE_URL --data-file=-
echo -n "replace-with-long-random-value" | \
gcloud secrets create JWT_SECRET --data-file=-
gcloud secrets add-iam-policy-binding DATABASE_URL \
--member="serviceAccount:$SERVICE_ACCOUNT" \
--role="roles/secretmanager.secretAccessor"
gcloud secrets add-iam-policy-binding JWT_SECRET \
--member="serviceAccount:$SERVICE_ACCOUNT" \
--role="roles/secretmanager.secretAccessor"
gcloud run services update "$SERVICE" \
--region "$REGION" \
--set-secrets "DATABASE_URL=DATABASE_URL:latest,JWT_SECRET=JWT_SECRET:latest"
Project-wide editor role देने के बजाय secret-level IAM बेहतर है। इससे गलती होने पर नुकसान सीमित रहता है।
Concurrency, min instances और cost
Concurrency का मतलब है कि एक container instance एक साथ कितनी requests process कर सकती है। ज्यादा value instance count कम कर सकती है, लेकिन database pool या external API limit पहले टूट सकती है।
gcloud run services update "$SERVICE" \
--region "$REGION" \
--concurrency 40 \
--min-instances 1 \
--max-instances 20 \
--cpu-throttling
Development या low-traffic projects में min-instances 0 रखें। Production webhook या API को cold start delay सहन नहीं है तो 1 या अधिक रखें। Webhook के लिए 20-40, BFF/API के लिए 40-80 से शुरू करें और p95 latency, DB connections और error rate देखकर बदलें।
Cloud Logging और rollback
Cloud Run request logs, container logs और system logs को Cloud Logging में भेजता है। Node.js में stdout/stderr पर log लिखना सामान्यतः काफी है।
gcloud run services logs read "$SERVICE" \
--region "$REGION" \
--limit 20
gcloud logging read \
"resource.type=cloud_run_revision AND resource.labels.service_name=$SERVICE" \
--limit 20 \
--format=json
हर deploy या config change एक immutable revision बनाता है। Problem हो तो traffic को stable revision पर वापस भेजें।
gcloud run revisions list \
--service "$SERVICE" \
--region "$REGION"
gcloud run services update-traffic "$SERVICE" \
--region "$REGION" \
--to-revisions myapp-api-00012-abc=100
Production से पहले यह review prompt चलाएं:
claude -p "
Act as a Cloud Run deployment reviewer.
Review package.json, Dockerfile, src/index.ts, and the gcloud commands below.
Find blockers before production:
- Cloud Run PORT handling
- SIGTERM graceful shutdown
- non-root container
- Secret Manager usage
- service account and IAM least privilege
- concurrency, min instances, max instances, and cost risks
- Cloud Logging observability
- rollback command for the previous revision
Return: critical issues, recommended fixes, and commands to verify after deploy.
"
आम pitfalls
बहुत बड़ी images build, push और cold start धीमे करती हैं। Normal environment variables में secrets डालने से shell history या CI logs में leak हो सकता है। min-instances 1 latency घटाता है, लेकिन idle time में भी billing करता है। बहुत high concurrency database और SaaS limits को overload कर सकती है। Rollback commands incident के समय नहीं, पहले अभ्यास में test करें।
References और next step
- Cloud Run documentation
- Cloud Run पर container images deploy करें
- Artifact Registry Docker authentication
- Cloud Run secrets configure करें
- Cloud Run logging
- Cloud Run rollback और traffic migration
- Claude Code Docker integration
- Claude Code AWS ECS/Fargate guide
- Claude Code security best practices
Cloud Run functions-only platforms से अधिक flexible और ECS/Kubernetes से कम operational heavy है। Team workflow में prompts, review checklists और deployment guardrails जोड़ने के लिए Claude Code training और consulting देखें।
Hands-on verification note
इस sample को local npm run dev, Docker /health, PORT handling और required environment validation के साथ check किया गया। Production से पहले real Artifact Registry permissions, Secret Manager IAM, Cloud Logging queries और update-traffic rollback drill जरूर करें।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.