TL;DR

从手动 git push 到完整 CI-CD 流水线:Gitee 触发构建、Cloudflare Pages 自动部署、构建失败 Slack 通知、一键回滚。读完本文,你的博客部署流程将达到生产级标准。

本文假设你已经:

  • 有一个运行中 Astro 博客
  • 了解 Git 基本操作(commit、push、branch)
  • 有 Cloudflare 账号和基础 DNS 知识
  • 不想再手动 SSH 到服务器执行构建

当前痛点:手动部署代价

手动部署典型流程:

# 1. 写文章
vim src/content/blog/new-post.md

# 2. 本地构建测试
npm run build

# 3. SSH 到服务器
ssh ubuntu@your-server

# 4. 拉代码
cd /home/ubuntu/CloakBlog && git pull

# 5. 安装依赖
npm install

# 6. 构建
npm run build

# 7. 重启预览
pm2 restart blog-preview

7 步操作,任何一步出错都可能导致线上故障。更危险是:没有记录谁在什么时候部署了什么。

目标架构

开发者 push 代码到 Gitee

Gitee Webhook 触发 Cloudflare Pages

CF Pages: npm install → npm run build → 部署到 Edge

构建结果通知(成功/失败)

线上生效(全球 CDN)

零 SSH,零手动操作,push 即部署。

Step 1:Cloudflare Pages 自动部署配置

1.1 连接 Git 仓库

Cloudflare Pages → Create a project → Connect to Git。

选择 Gitee(如果不在列表中,用 GitHub 镜像)。

1.2 构建配置

配置项说明
Framework presetAstro自动识别构建命令
Build commandnpm run build如果有后处理脚本用 npm run build && python3 fix_wrangler.py
Build output directorydistAstro 默认输出目录
Node.js version20在 Environment variables 中设置 NODE_VERSION=20

1.3 环境变量

NODE_VERSION=20
ASTRO_TELEMETRY_DISABLED=1

如果用了 SSR 模式(@astrojs/cloudflare),CF Pages 会自动检测 wrangler.tomlastro.config.mjs 中的适配器配置。

Step 2:多环境部署

实际项目至少需要两个环境:预览(Preview)生产(Production)

2.1 分支策略

master  → Production (blog.example.com)
develop → Preview (develop.blog.example.com)
feature/xxx → Preview (xxx.blog.example.com)

CF Pages 自动为每个分支创建预览 URL。master 分支的部署绑定自定义域名,其他分支用 .<branch>.pages.dev 域名。

2.2 环境变量隔离

在 CF Pages 的 Settings → Environment variables 中,为 Production 和 Preview 分别配置:

Production:
  SITE_URL=https://blog.example.com
  ANALYTICS_ID=prod-xxx

Preview:
  SITE_URL=https://develop.blog.pages.dev
  ANALYTICS_ID=dev-xxx

Astro 代码中读取:

// astro.config.mjs
export default defineConfig({
  site: process.env.SITE_URL || 'https://localhost:4321',
});

Step 3:构建优化

3.1 构建缓存

CF Pages 默认不缓存 node_modules,每次从头安装依赖。对于 100+ 依赖的项目,这会增加 30-60s 构建时间。

优化方案:使用 pnpm 代替 npm,依赖安装快 2-3 倍。

# CF Pages Build command
npm install -g pnpm && pnpm install && pnpm run build

3.2 增量构建

Astro 6.x 支持内容缓存,只重新构建变更页面:

// astro.config.mjs
export default defineConfig({
  build: {
    // 启用增量构建(实验性功能)
    incremental: true,
  },
});

100 篇文章博客,全量构建 3s → 增量构建 0.8s。

3.3 构建超时配置

CF Pages 默认构建超时 20 分钟。如果博客文章很多(1000+),可能需要调整:

# wrangler.toml(Cloudflare Workers 配置)
[site]
  bucket = "./dist"

[build]
  command = "npm run build"
  timeout = 1800  # 30 分钟

Step 4:监控与告警

4.1 构建状态通知

CF Pages 支持 Slack/Discord 通知:

Settings → Builds & deployments → Build notifications → Add notification

选择 Slack webhook,配置通知类型:

  • Deployment succeeded:部署成功
  • Deployment failed:部署失败(必须开)

4.2 线上可用性监控

用免费 UptimeRobot 监控博客可用性:

  1. 注册 UptimeRobot
  2. 添加监控:https://blog.example.com,间隔 5 分钟
  3. 配置告警:邮件 + Slack

4.3 Web Vitals 监控

CF Pages 内置 Web Analytics(免费),在 Dashboard → Analytics 查看:

  • Core Web Vitals(LCP、FID、CLS)
  • 页面浏览量
  • 热门页面

开启方式:

# 安装 CF Analytics 集成
npx astro add cloudflare

或在 astro.config.mjs 中:

import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  adapter: cloudflare({
    platformProxy: {
      enabled: true,
    },
  }),
});

Step 5:回滚策略

5.1 CF Pages 一键回滚

CF Pages 保留每次部署记录。回滚只需:

Dashboard → Deployments → 选择上一个成功部署 → Rollback to this deployment

耗时 < 10 秒,全球生效。

5.2 Git 回滚(更精确)

如果需要回滚到特定版本:

# 查看提交历史
git log --oneline -10

# 回滚到指定版本
git revert <commit-hash>
git push origin master

# CF Pages 自动触发新部署(内容是回滚后的)

注意git revertgit reset --hard 更安全,因为 revert 是一个新 commit,不会丢失历史。

5.3 紧急回滚脚本

创建 scripts/rollback.sh

#!/bin/bash
# 用法: ./rollback.sh <commit-hash>
COMMIT=$1

if [ -z "$COMMIT" ]; then
  echo "Usage: ./rollback.sh <commit-hash>"
  echo "Recent commits:"
  git log --oneline -5
  exit 1
fi

echo "Rolling back to $COMMIT..."
git revert --no-edit "$COMMIT"
git push origin master
echo "Done. CF Pages will auto-deploy."

Step 6:安全加固

6.1 访问控制

CF Pages 预览 URL 默认公开。如果不想暴露 develop 分支的内容:

Settings → Access policies → Add policy

配置 Only allow access from:

  • 特定 IP
  • Email 域名(如 @yourcompany.com
  • Cloudflare Access SSO

6.2 安全头

_headers 文件(放在 public/ 目录)中配置安全头:

/*
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
  Permissions-Policy: camera=(), microphone=(), geolocation=()
  Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com

6.3 依赖安全审计

在 CI 中加入 npm audit

# build.sh 中添加
echo "Running security audit..."
npm audit --audit-level=high || exit 1

echo "Building..."
npm run build

有高危漏洞时构建失败,阻止部署。

Step 7:性能优化清单

7.1 缓存策略

CF Pages 默认缓存静态资源。对于 SSR 页面,需要手动配置缓存:

// src/middleware.ts
export const onRequest = async (context, next) => {
  const response = await next();

  // 静态页面缓存 1 小时
  if (context.url.pathname.startsWith('/blog/')) {
    response.headers.set('Cache-Control', 'public, max-age=3600, s-maxage=86400');
  }

  // 首页缓存 5 分钟
  if (context.url.pathname === '/') {
    response.headers.set('Cache-Control', 'public, max-age=300, s-maxage=3600');
  }

  return response;
};

7.2 图片优化

使用 Astro 内置 <Image> 组件自动生成 WebP 和多尺寸:

---
import { Image } from 'astro:assets';
import hero from '../images/hero.png';
---
<Image src={hero} alt="Hero" widths={[400, 800, 1200]} sizes="(max-width: 768px) 400px, 800px" />

7.3 字体优化

<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&display=swap" rel="stylesheet" />

preconnect 提前建立连接,字体加载快 100-200ms。

Step 8:完整流水线验证

8.1 端到端测试

部署后自动验证关键页面可访问:

#!/bin/bash
# scripts/verify-deploy.sh
URL="https://blog.example.com"

echo "Verifying deployment..."

# 检查首页
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
if [ "$STATUS" != "200" ]; then
  echo "❌ Homepage returned $STATUS"
  exit 1
fi
echo "✅ Homepage: $STATUS"

# 检查 RSS
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL/rss.xml")
if [ "$STATUS" != "200" ]; then
  echo "❌ RSS returned $STATUS"
  exit 1
fi
echo "✅ RSS: $STATUS"

# 检查 sitemap
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL/sitemap-index.xml")
if [ "$STATUS" != "200" ]; then
  echo "❌ Sitemap returned $STATUS"
  exit 1
fi
echo "✅ Sitemap: $STATUS"

echo "All checks passed!"

8.2 部署检查清单

每次部署后验证:

  • 首页 200
  • 文章页 200
  • RSS 可访问
  • Sitemap 可访问
  • 404 页面正常
  • Web Vitals 在正常范围(LCP < 2.5s)
  • 移动端显示正常

Trade-offs

决策优点代价
CF Pages 自动部署零运维、全球 CDN依赖 Cloudflare 生态
SSR 模式动态路由灵活TTFB 比 SSG 多 100ms
分支预览功能验证安全每个分支都消耗 CF Pages 额度
安全头防 XSS/点击劫持CSP 可能阻断第三方脚本
npm audit CI 检查阻止高危依赖可能有误报

写在

从手动部署到自动化流水线核心纪律

  1. 每次变更走 Git:不 SSH 直改服务器
  2. 构建失败不发布:CI 是守门员
  3. 回滚比修复快:出问题先回滚,再排查
  4. 监控不能少:用户比你自己先发现故障

这四条做到,部署运维就入门了。

延伸阅读

种下你的想法

在花园里留下一条评论,和这篇文章一起生长。

COMMENTS