
关于
构建生产级 GCP Cloud Run 无服务器应用的专业技能。
name: gcp-cloud-run description: 专注于在 GCP 上构建生产级无服务器应用的技能。涵盖 Cloud Run 服务(容器化)、Cloud Run Functions(事件驱动)、冷启动优化以及基于 Pub/Sub 的事件驱动架构。 risk: unknown source: vibeship-spawner-skills (Apache 2.0) date_added: 2026-02-27
GCP Cloud Run
专注于在 GCP 上构建生产级无服务器应用的技能。涵盖 Cloud Run 服务(容器化)、Cloud Run Functions(事件驱动)、冷启动优化以及基于 Pub/Sub 的事件驱动架构。
原则
- Cloud Run 用于容器,Functions 用于简单的事件处理器
- 通过启动 CPU 加速和最小实例数优化冷启动
- 根据工作负载设置并发数(从 8 开始,逐步调整)
- 内存包含 /tmp 文件系统——需要相应规划
- 仅在需要时使用 VPC 连接器(会增加延迟)
- 容器应快速启动且保持无状态
- 优雅地处理信号以实现干净关闭
模式
Cloud Run 服务模式
Cloud Run 上的容器化 Web 服务
适用场景:Web 应用和 API,需要任意运行时或库,具有多个端点的复杂服务,无状态容器化工作负载
# Dockerfile - Multi-stage build for smaller image
FROM node:20-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:20-slim
WORKDIR /app
# Copy only production dependencies
COPY --from=builder /app/node_modules ./node_modules
COPY src ./src
COPY package.json ./
# Cloud Run uses PORT env variable
ENV PORT=8080
EXPOSE 8080
# Run as non-root user
USER node
CMD ["node", "src/index.js"]
// src/index.js
const express = require('express');
const app = express();
app.use(express.json());
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
// API routes
app.get('/api/items/:id', async (req, res) => {
try {
const item = await getItem(req.params.id);
res.json(item);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
const PORT = process.env.PORT || 8080;
const server = app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
# cloudbuild.yaml
steps:
# Build the container image
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/my-service:$COMMIT_SHA', '.']
# Push the container image
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/$PROJECT_ID/my-service:$COMMIT_SHA']
# Deploy to Cloud Run
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args:
- 'run'
- 'deploy'
- 'my-service'
- '--image=gcr.io/$PROJECT_ID/my-service:$COMMIT_SHA'
- '--region=us-central1'
- '--platform=managed'
- '--allow-unauthenticated'
- '--memory=512Mi'
- '--cpu=1'
- '--min-instances=1'
- '--max-instances=100'
- '--concurrency=80'
- '--cpu-boost'
images:
- 'gcr.io/$PROJECT_ID/my-service:$COMMIT_SHA'
目录结构
project/ ├── Dockerfile ├── .dockerignore ├── src/ │ ├── index.js │ └── routes/ ├── package.json └── cloudbuild.yaml
Gcloud 部署
直接使用 gcloud 部署
gcloud run deploy my-service
--source .
--region us-central1
--allow-unauthenticated
--memory 512Mi
--cpu 1
--min-instances 1
--max-instances 100
--concurrency 80
--cpu-boost
Cloud Run Functions 模式
事件驱动函数(前身为 Cloud Functions)
适用场景:简单的事件处理器,Pub/Sub 消息处理,Cloud Storage 触发器,HTTP Webhooks
// HTTP Function
// index.js
const functions = require('@google-cloud/functions-framework');
functions.http('helloHttp', (req, res) => {
const name = req.query.name || req.body.name || 'World';
res.send(`Hello, ${name}!`);
});
// Pub/Sub Function
const functions = require('@google-cloud/functions-framework');
functions.cloudEvent('processPubSub', (cloudEvent) => {
// Decode Pub/Sub message
const message = cloudEvent.data.message;
const data = message.data
? JSON.parse(Buffer.from(message.data, 'base64').toString())
: {};
console.log('Received message:', data);
// Process message
processMessage(data);
});
// Cloud Storage Function
const functions = require('@google-cloud/functions-framework');
functions.cloudEvent('processStorageEvent', async (cloudEvent) => {
const file = cloudEvent.data;
console.log(`Event: ${cloudEvent.type}`);
console.log(`Bucket: ${file.bucket}`);
console.log(`File: ${file.name}`);
if (cloudEvent.type === 'google.cloud.storage.object.v1.finalized') {
// Process new file
await processNewFile(file.bucket, file.name);
}
});
兼容工具
Claude CodeCursor
标签
后端开发
