名称: gcp-cloud-run 描述: “专门用于在GCP上构建生产就绪的无服务器应用程序的技能。涵盖Cloud Run服务(容器化)、Cloud Run Functions(事件驱动)、冷启动优化以及使用Pub/Sub的事件驱动架构。” 来源: vibeship-spawner-skills (Apache 2.0)
GCP Cloud Run
模式
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'
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') {
await processUploadedFile(file.bucket, file.name);
}
});
# Deploy HTTP function
gcloud functions deploy hello-http \
--gen2 \
--runtime nodejs20 \
--trigger-http \
--allow-unauthenticated \
--region us-central1
# Deploy Pub/Sub function
gcloud functions deploy process-messages \
--gen2 \
--runtime nodejs20 \
--trigger-topic my-topic \
--region us-central1
# Deploy Cloud Storage function
gcloud functions deploy process-uploads \
--gen2 \
--runtime nodejs20 \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=my-bucket" \
--region us-central1
冷启动优化模式
最小化Cloud Run的冷启动延迟
使用场景: [‘延迟敏感型应用程序’, ‘面向用户的API’, ‘高流量服务’]
1. 启用启动CPU提升
gcloud run deploy my-service \
--cpu-boost \
--region us-central1
2. 设置最小实例数
gcloud run deploy my-service \
--min-instances 1 \
--region us-central1
3. 优化容器镜像
# Use distroless for minimal image
FROM node:20-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM gcr.io/distroless/nodejs20-debian12
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY src ./src
CMD ["src/index.js"]
4. 延迟初始化重量级依赖
// Lazy load heavy libraries
let bigQueryClient = null;
function getBigQueryClient() {
if (!bigQueryClient) {
const { BigQuery } = require('@google-cloud/bigquery');
bigQueryClient = new BigQuery();
}
return bigQueryClient;
}
// Only initialize when needed
app.get('/api/analytics', async (req, res) => {
const client = getBigQueryClient();
const results = await client.query({...});
res.json(results);
});
5. 增加内存(更多CPU)
# Higher memory = more CPU during startup
gcloud run deploy my-service \
--memory 1Gi \
--cpu 2 \
--region us-central1
反模式
❌ 没有设置并发数为1的CPU密集型工作
为何不好: CPU在并发请求之间共享。CPU密集型工作会使其他请求饿死,导致超时。
❌ 向/tmp写入大文件
为何不好: /tmp是一个内存文件系统。大文件会消耗你的内存分配,并可能导致OOM错误。
❌ 长时间运行的后台任务
为何不好: Cloud Run在不处理请求时将CPU限制到接近零。后台任务将非常慢或停滞。
⚠️ 注意事项
| 问题 | 严重性 | 解决方案 |
|---|---|---|
| 问题 | 高 | ## 计算内存包括/tmp使用量 |
| 问题 | 高 | ## 设置适当的并发数 |
| 问题 | 高 | ## 启用CPU始终分配 |
| 问题 | 中 | ## 配置连接池与保持活动 |
| 问题 | 高 | ## 启用启动CPU提升 |
| 问题 | 中 | ## 明确设置执行环境 |
| 问题 | 中 | ## 设置一致的超时 |